string – How to get the position of a character in Python?

The Question :

577 people think this question is useful

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

The Question Comments :

The Answer 1

762 people think this answer is useful

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 ValueError.

Using find()

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

Using index()

>>> myString = 'Position of a character'
>>> myString.index('s')
>>> 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.


string.index(s, sub[, start[, end]])
Like find() but raise ValueError when the substring is not found.

The Answer 2

145 people think this answer is useful

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]

The Answer 3

50 people think this answer is useful
>>> s="mystring"
>>> s.index("r")
>>> s.find("r")

“Long winded” way

>>> for i,c in enumerate(s):
...   if "r"==c: print i

to get substring,

>>> s="mystring"
>>> s[4:10]

The Answer 4

19 people think this answer is useful

Just for completion, in the case I want to find the extension in a file name in order to check it, I need to find the last ‘.’, in this case use rfind:

path = 'toto.titi.tata..xls'

in my case, I use the following, which works whatever the complete file name is:

filename_without_extension = complete_name[:complete_name.rfind('.')]

The Answer 5

15 people think this answer is useful

What happens when the string contains a duplicate character? from my experience with index() I saw that for duplicate you get back the same index.

For example:

s = 'abccde'
for c in s:
    print('%s, %d' % (c, s.index(c)))

would return:

a, 0
b, 1
c, 2
c, 2
d, 4

In that case you can do something like that:

for i, character in enumerate(my_string):
   # i is the position of the character in the string

The Answer 6

10 people think this answer is useful

Perhaps you’d like to have a look at the documentation to find out what the difference between the two is.

The Answer 7

8 people think this answer is useful

A character might appear multiple times in a string. For example in a string sentence, position of e is 1, 4, 7 (because indexing usually starts from zero). but what I find is both of the functions find() and index() returns first position of a character. So, this can be solved doing this:

def charposition(string, char):
    pos = [] #list to store positions for each 'char' in 'string'
    for n in range(len(string)):
        if string[n] == char:
    return pos

s = "sentence"
print(charposition(s, 'e')) 

#Output: [1, 4, 7]

The Answer 8

1 people think this answer is useful

more_itertools.locate is a third-party tool that finds all indicies of items that satisfy a condition.

Here we find all index locations of the letter "i".

import more_itertools as mit

s = "supercalifragilisticexpialidocious"
list(mit.locate(s, lambda x: x == "i"))
# [8, 13, 15, 18, 23, 26, 30]

The Answer 9

-1 people think this answer is useful

A solution with numpy for quick access to all indexes:

string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')

Add a Comment