Python String index() method example

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.

Basically, we use the index() to get the lowest index of a substring within a string.

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

The following example shows how to use the index() method to find the substring 'Code' in the string 'Source Code Examples.':
s = 'Source Code Examples'
position = s.index('Code')

print(position)

Output:

7
The following example uses the index() method to find the substring 'Code' in the string 'Source Code Examples' within the slice str[1:]:

s = 'Source Code Examples, Source'
position = s.index('Source', 1)

print(position)

Output:

22
The following example raises a ValueError because the substring 'Python' doesn’t exist in the string 'Source Code Examples':

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

  1. Python string literals
  2. Python string length example
  3. Python String join() method example
  4. Python string split() method example
  5. Python String index() method example
  6. Python string find() method example
  7. Python string startswith() method example
  8. Python string endswith() method example
  9. Python String lower() method example
  10. Python String upper() method example
  11. Python string title() method example
  12. Python string capitalize() method example
  13. Python string islower() method example
  14. Python string istitle() method example
  15. Python string isupper() method example
  16. Python string swapcase() method example
  17. Python string strip() method example
  18. Python string replace() method example
  19. Python string isdigit() method example
  20. Python string isdecimal() method example
  21. Python string isnumeric() method example
  22. Python string isalpha() method example
  23. Python string isalnum() method example


Comments