How to Get the Psition of a Character in Python

Created
Modified

Using find Method

The str.find(sub[, start[, end]]) method returns the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. For example,

#!/usr/bin/python3

a = "There are two"

i = a.find('r')
print(i)

i = a.find('rb')
print(i)
3
-1

Using index Method

Like find(), but raise ValueError when the substring is not found.

The following example should cover whatever you are trying to do:

#!/usr/bin/python3

a = "There are two"

i = a.index('r')
print(i)

i = a.index('rb')
3
ValueError: substring not found

Using List Comprehension

If you need to find all positions of a character in a string, you can do the following:

#!/usr/bin/python3

s = "There are two"

l = [pos for pos, char in enumerate(s) if char == 'r' ]
print(l)
[3, 7]

Related Tags