How to get the position of a character in Python?
How can I get the position of a character inside a string in python?
There are two string methods for this,
index(). The difference between the two is what happens when the search string isn't found.
>>> myString = 'Position of a character' >>> myString.find('s') 2 >>> myString.find('x') -1
>>> myString = 'Position of a character' >>> myString.index('s') 2 >>> myString.index('x') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found
From the Python manual
string.find(s, sub[, start[, end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained in
-1on failure. Defaults for start and end and interpretation of negative values is the same as for slices.
string.index(s, sub[, start[, end]])
ValueErrorwhen the substring is not found.
Read more... Read less...
Just for a sake of completeness, if you need to find all positions of a character in a string, you can do the following:
s = 'shak#spea#e' c = '#' print [pos for pos, char in enumerate(s) if char == c]
which will return
>>> s="mystring" >>> s.index("r") 4 >>> s.find("r") 4
"Long winded" way
>>> for i,c in enumerate(s): ... if "r"==c: print i ... 4
to get substring,
>>> s="mystring" >>> s[4:10] 'ring'
Just for completion, in the case I want to find the extension in a file name in order to check it, I need to find the last '.', in this case use rfind:
path = 'toto.titi.tata..xls' path.find('.') 4 path.rfind('.') 15
in my case, I use the following, which works whatever the complete file name is:
filename_without_extension = complete_name[:complete_name.rfind('.')]
What happens when the string contains a duplicate character?
from my experience with
index() I saw that for duplicate you get back the same index.
s = 'abccde' for c in s: print('%s, %d' % (c, s.index(c)))
a, 0 b, 1 c, 2 c, 2 d, 4
In that case you can do something like that:
for i, character in enumerate(my_string): # i is the position of the character in the string