In this source code example, we will demonstrate how to use the Python string index() method to get the index of a substring in a string.
Python
Python String
Basically, we use the index() to get the lowest index of a substring within a string.
The following shows the syntax of the index() method:The following example shows how to use the index() method to find the substring 'Code' in the string 'Source Code Examples.': The following example uses the index() method to find the substring 'Code' in the string 'Source Code Examples' within the slice str[1:]:
The following example raises a ValueError because the substring 'Python' doesn’t exist in the string 'Source Code Examples':
Python String index() method
The string index() method returns the lowest index of a substring in a string.The following shows the syntax of the index() method:
str.index(sub[, start[, end]])The index() method has three parameters:
- sub is the substring to search for in the str.
- start and end parameters are interpreted as in the slice notation str[start:end]. The slice specifies where to look for the substring sub. Both start and end parameters are optional.
Python String index() method examples
s = 'Source Code Examples'
position = s.index('Code')
print(position)
Output:
7
s = 'Source Code Examples, Source'
position = s.index('Source', 1)
print(position)
Output:
22
s = 'Source Code Examples'
position = s.index('Python')
print(position)
Output:
Traceback (most recent call last):
File "main.py", line 2, in <module>
position = s.index('Python')
ValueError: substring not found
Related Python String Examples
- Python string literals
- Python string length example
- Python String join() method example
- Python string split() method example
- Python String index() method example
- Python string find() method example
- Python string startswith() method example
- Python string endswith() method example
- Python String lower() method example
- Python String upper() method example
- Python string title() method example
- Python string capitalize() method example
- Python string islower() method example
- Python string istitle() method example
- Python string isupper() method example
- Python string swapcase() method example
- Python string strip() method example
- Python string replace() method example
- Python string isdigit() method example
- Python string isdecimal() method example
- Python string isnumeric() method example
- Python string isalpha() method example
- Python string isalnum() method example
Comments
Post a Comment