How can I get the position of a character inside a string in Python?
The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found then it returns -1. Parameters: sub: It is the substring that needs to be searched in the given string.
There are two string methods for this, find()
and index()
. The difference between the two is what happens when the search string isn't found. find()
returns -1
and index()
raises a ValueError
.
find()
>>> myString = 'Position of a character' >>> myString.find('s') 2 >>> myString.find('x') -1
index()
>>> 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 ins[start:end]
. Return-1
on failure. Defaults for start and end and interpretation of negative values is the same as for slices.
And:
string.index(s, sub[, start[, end]])
Likefind()
but raiseValueError
when the substring is not found.
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 print: [4, 9]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With