Reputation: 87
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:"
Upvotes: 3
Views: 25850
Reputation: 5632
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
Upvotes: 9