3

I am relatively new in Python. I wanted to know if is there any possibility for me to get only the E: from the string below:

p="\\.\E:"
7
  • p[-2] prints out 'E' Commented Nov 25, 2019 at 16:53
  • I want to print E: Commented Nov 25, 2019 at 16:54
  • 1
    Then use a slice: p[-2:] Commented Nov 25, 2019 at 16:54
  • 1
    BTW, you need to escape the second slash, or use a raw string. Commented Nov 25, 2019 at 16:55
  • 1
    What does this have to do with tkinter or paragraph? Commented Nov 25, 2019 at 16:56

1 Answer 1

9

Sure you can do this using slicing.

p="\\.\E:"
result = p[-2:]  # Operates like: p[len(p) - 2 : len(p)]
# Where the colon (:) operator works as a delimiter that
# represent an "until" range. If the left hand starting
# value is missing it assumes a default 
# starting position of 0, if the right hand end position 
# value is missing it assumes the default to be the length 
# of the string operated upon. If a negative value is 
# passed to either the left or right hand value, it 
# assumes the length of the string - the value. 
print("result: " + result)
>> result: E:

Let's look at what happens above:

We slice the string p at position -2, this is because we want a generic approach that will always start stripping from the last two characters, this without knowing how many characters in length the string is.

If we knew it's always going to be a fix number of characters in length, say 4 characters then we could do:

result = p[2:]  # Every character from 2 and on wards
# Works like: p[2:len(p)] 

This would mean, result should contain every character that comes after index 2, this is because we do not specify a max value after the colon operator :, if we wanted to, for our previous example, we could do:

result = p[2:4]  # Every character from position 2 until 4

Thus, if one were to instead want the first two characters, one could do:

result = p[:2]  # Every character until position 2

Or:

result = p[0:2]  # Every character from 0 until 2

You might also want to check out: https://www.w3schools.com/python/gloss_python_string_slice.asp

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.