Advertisement
Advertisement


How to get the position of a character in Python?


Question

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

2013/06/03
1
543
6/3/2013 8:55:55 PM


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 return [4, 9]

2018/05/15

>>> 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'
2010/02/19

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'
path.find('.')
4
path.rfind('.')
15

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

filename_without_extension = complete_name[:complete_name.rfind('.')]
2017/12/06

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
2017/08/31

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.

2014/04/11

Source: https://stackoverflow.com/questions/2294493
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]