Hi all,
How can i get the position of a character in a string in python.
regards
Arun
Hi all,
How can i get the position of a character in a string in python.
regards
Arun
There are two string methods for this, find and index.
Example:
>>> str = "Position of a character"
>>> str.index('s')
2
The difference is that find returns -1 when what you're looking for isn't found. index throws an exception.
str.find(sub[, start[, end]]) Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
And:
str.index(sub[, start[, end]]) Like find(), but raise ValueError when the substring is not found.
>>> 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'
string.find(character)
string.index(character)
Perhaps you'd like to have a look at the documentation to find out what the difference between the two is.