How can I get the position of a character inside a string in python?
-
10And this will show you all the positions of a character in a string – Salvador Dali Sep 26 '15 at 8:01
-
You will find your answer here: stackoverflow.com/a/46742928/8584198 – Saeed Zahedian Abroodi Dec 2 at 6:31
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')
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 ins[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]])
Likefind()
but raiseValueError
when the substring is not found.
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]
-
1
-
16@Sean : print statement was removed. Only the function form remains. Irritating, but the answer is simply to change that final line to:
print( [pos for pos, char in enumerate(s) if char == c])
– The Nate Aug 26 '16 at 5:14 -
3
foo = ( [pos for pos, char in enumerate(s) if char == c])
will put the coordinates foo in a list format. I find this really helpful – 3nrique0 Feb 24 '17 at 17:01
>>> 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'
-
1Thanks Tell me how can we get the substring of a string according to the positions given... – user244470 Feb 19 '10 at 6:50
-
1@arung: to get the substring use slicing:
str[from:to]
wherefrom
andto
are indices – Eli Bendersky Feb 19 '10 at 6:57 -
-
s.search() raises a ValueError when the substring is not found. s.find() returns -1 if the substring isn't found. – Praxiteles Jan 29 '17 at 9:08
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
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('.')]
-
This is helpful for finding the extent of a string. For example, finding a dictionary could be:
left = q.find("{"); right = q.rfind("}")
. – ximiki Oct 6 '17 at 16:51
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.
-
From that linked documentation: s.search() raises a ValueError when the substring is not found. s.find() returns -1 if the substring isn't found. – Praxiteles Jan 29 '17 at 9:10
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:
pos.append(n)
return pos
s = "sentence"
print(charposition(s, 'e'))
#Output: [1, 4, 7]
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]