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
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.