Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the position of a character in Python?

Tags:

python

string

How can I get the position of a character inside a string in Python?

like image 207
user244470 Avatar asked Feb 19 '10 06:02

user244470


People also ask

How do you find the position of a character in a string?

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.

How do you find the position of a word in a string in Python?

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.


2 Answers

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.

Using find()

>>> myString = 'Position of a character' >>> myString.find('s') 2 >>> myString.find('x') -1 

Using 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 

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 s[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]])
Like find() but raise ValueError when the substring is not found.

like image 56
Eli Bendersky Avatar answered Sep 21 '22 08:09

Eli Bendersky


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]

like image 22
Salvador Dali Avatar answered Sep 21 '22 08:09

Salvador Dali