tags:

views:

52

answers:

3

Hi all,

How can i get the position of a character in a string in python.

regards

Arun

+4  A: 

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.

Eli Bendersky
and of course the first character is position 0
gnibbler
+1  A: 
>>> 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'
ghostdog74
ThanksTell me how can we get the substring of a string according to the positions given...
@arung: to get the substring use slicing: `str[from:to]` where `from` and `to` are indices
Eli Bendersky
A: 

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.

John Machin
thanks....function to get the substring according to the positions given