In this tutorial, we will learn about the Python index[] method with the help of examples.
The index[]
method returns the index of a substring inside the string [if found]. If the substring is not found, it raises an exception.
Example
text = 'Python is fun'
# find the index of is
result = text.index['is']
print[result]
# Output: 7
index[] Syntax
It's syntax is:
str.index[sub[, start[, end]] ]
index[] Parameters
The index[]
method takes
three parameters:
- sub - substring to be searched in the string str.
- start and end[optional] - substring is searched within str[start:end]
index[] Return Value
- If substring exists inside the string, it returns the lowest index in the string where substring is found.
- If substring doesn't exist inside the string, it raises a ValueError exception.
The index[]
method is similar to the find[] method for strings.
The only difference is that find[] method returns -1 if the substring is not found, whereas index[]
throws an exception.
Example 1: index[] With Substring argument Only
sentence = 'Python programming is fun.'
result = sentence.index['is fun']
print["Substring 'is fun':", result]
result = sentence.index['Java']
print["Substring 'Java':", result]
Output
Substring 'is fun': 19 Traceback [most recent call last]: File "", line 6, in result = sentence.index['Java'] ValueError: substring not found
Note: Index in Python starts from 0 and not 1. So the occurrence is 19 and not 20.
Example 2: index[] With start and end Arguments
sentence = 'Python programming is fun.'
# Substring is searched in 'gramming is fun.'
print[sentence.index['ing', 10]]
# Substring is searched in 'gramming is '
print[sentence.index['g is', 10, -4]]
# Substring is searched in 'programming'
print[sentence.index['fun', 7, 18]]
Output
15 17 Traceback [most recent call last]: File "", line 10, in print[quote.index['fun', 7, 18]] ValueError: substring not found
How can I get the position of a character inside a string in Python?
bad_coder
9,12919 gold badges37 silver badges60 bronze badges
asked Feb 19, 2010 at 6:32
0
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 "", line 1, in
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.
Tomerikoo
16.5k15 gold badges37 silver badges54 bronze badges
answered Feb 19, 2010 at 6:35
Eli BenderskyEli Bendersky
252k87 gold badges343 silver badges406 bronze badges
1
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]
Jolbas
7375 silver badges15 bronze badges
answered Sep 26, 2015 at 7:59
Salvador DaliSalvador Dali
203k142 gold badges684 silver badges744 bronze badges
4
>>> 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'
answered Feb 19, 2010 at 6:36
ghostdog74ghostdog74
313k55 gold badges252 silver badges339 bronze badges
4
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['.']]
answered Sep 28, 2017 at 6:37
A.JolyA.Joly
2,1072 gold badges17 silver badges23 bronze badges
1
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
answered Jul 1, 2015 at 12:40
DimSarakDimSarak
4422 gold badges5 silver badges11 bronze badges
1
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.
Brad Koch
18.2k18 gold badges107 silver badges135 bronze badges
answered Feb 19, 2010 at 6:37
John MachinJohn Machin
79.3k11 gold badges137 silver badges182 bronze badges
1
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]
answered Sep 16, 2018 at 9:33
itssubasitssubas
1622 silver badges11 bronze badges
If you want to find the first match.
Python has a in-built string method that does the work: index[].
string.index[value, start, end]
Where:
- Value: [Required] The value to search for.
- start: [Optional] Where to start the search. Default is 0.
- end: [Optional] Where to end the search. Default is to the end of the string.
def character_index[]:
string = "Hello World! This is an example sentence with no meaning."
match = "i"
return string.index[match]
print[character_index[]]
> 15
If you want to find all the matches.
Let's say you need all the indexes where the character match
is and
not just the first one.
The pythonic way would be to use enumerate[]
.
def character_indexes[]:
string = "Hello World! This is an example sentence with no meaning."
match = "i"
indexes_of_match = []
for index, character in enumerate[string]:
if character == match:
indexes_of_match.append[index]
return indexes_of_match
print[character_indexes[]]
# [15, 18, 42, 53]
Or even better with a list comprehension:
def character_indexes_comprehension[]:
string = "Hello World! This is an example sentence with no meaning."
match = "i"
return [index for index, character in enumerate[string] if character == match]
print[character_indexes_comprehension[]]
# [15, 18, 42, 53]
answered Jan 26, 2021 at 5:01
Guzman OjeroGuzman Ojero
2,02018 silver badges18 bronze badges
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"
.
Given
import more_itertools as mit
text = "supercalifragilisticexpialidocious"
search = lambda x: x == "i"
Code
list[mit.locate[text, search]]
# [8, 13, 15, 18, 23, 26, 30]
answered Feb 9, 2018 at 0:46
pylangpylang
36k11 gold badges119 silver badges110 bronze badges
A solution with numpy for quick access to all indexes:
string_array = np.array[list[my_string]]
char_indexes = np.where[string_array == 'C']
answered Jan 15, 2020 at 20:40
SebSeb
3024 silver badges6 bronze badges
2
Most methods I found refer to finding the first substring in a string. To find all the substrings, you need to work around.
For example:
Define the string
vars = 'iloveyoutosimidaandilikeyou'
Define the substring
key = 'you'
Define a function that can find the location for all the substrings within the string
def find_all_loc[vars, key]:
pos = []
start = 0
end = len[vars]
while True:
loc = vars.find[key, start, end]
if loc is -1:
break
else:
pos.append[loc]
start = loc + len[key]
return pos
pos = find_all_loc[vars, key]
print[pos]
[5, 24]
Emi OB
2,3433 gold badges10 silver badges24 bronze badges
answered Nov 5, 2021 at 8:44