How do you get an index of an element in a string python?

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

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Python String index() Method allows a user to find the index of the first occurrence of an existing substring inside a given string.

    Python String index() Method Syntax:

    Syntax:  string_obj.index(substring, begp, endp)

    Parameters: 

    • substring : The string to be searched for.
    • begp (default : 0) : This function specifies the position from where search has to be started. 
    • endp (default : length of string) : This function specifies the position from where search has to end.

    Return:  Returns the first position of the substring found.

    Exception:  Raises ValueError if argument string is not found or index is out of range.

    Python String index() Method Example:

    Python3

    string = 'random'

    print("index of 'and' in string:", string.index('and'))

    Output:

    index of 'and' in string: 1

    Example 1: Basic usage of Python String index() Method

    Python

    ch = "geeksforgeeks"

    ch2 = "geeks"

    pos = ch.index(ch2,2)

    print("The first position of geeks after 2nd index : ",end="")

    print(pos)

    Output: 

    The first position of geeks after 2nd index : 8

    Note: The index() method is similar to find(). The only difference is find() returns -1 if the searched string is not found and index() throws an exception in this case.

    Example 2: Python String index() With start and end Arguments

    Python3

    test_string = "1234gfg4321"

    print(test_string.index('gfg', 4, 8))

    print(test_string.index("21", 8, len(test_string)))

    print(test_string.index("32", 5, -1))

    Output:

    4
    9
    8

    Exception when using Python String index() Method

    ValueError: This error is raised in the case when the argument string is not found in the target string.

    Python

    ch = "geeksforgeeks"

    ch2 = "gfg"

    pos = ch.index(ch2)

    print("The first position of gfg is : ",end="")

    print(pos)

    Output:

    Traceback (most recent call last):
      File "/home/aa5904420c1c3aa072ede56ead7e26ab.py", line 12, in 
        pos = ch.index(ch2)
    ValueError: substring not found

    Practical Application

    Python String index() Method function is used to extract the suffix or prefix length after or before the target word. The example below displays the total bit length of an instruction coming from AC voltage given information in a string.

    Python

    VOLTAGES = ["001101 AC", "0011100 DC", "0011100 AC", "001 DC"]

    TYPE = "AC"

    SUM_BITS = 0

    for i in VOLTAGES:

        ch = i

        if ch[len(ch) - 2] != "D":

            bit_len = ch.index(TYPE) - 1

            SUM_BITS = SUM_BITS + bit_len

    print("The total bit length of AC is : ", SUM_BITS)

    Output: 

    The total bit length of AC is : 13

    Can you take the index of a string in Python?

    The Python string data type is a sequence made up of one or more individual characters that could consist of letters, numbers, whitespace characters, or symbols. Because a string is a sequence, it can be accessed in the same ways that other sequence-based data types are, through indexing and slicing.

    How do I print a specific index of a string in Python?

    all you need to do is add brackets with the char number to the end of the name of the string you want to print, i.e. Show activity on this post. Well if you know the character you want to search you can use this approach. you can change the print statement according to your logic.

    How do you find the index of a specific string?

    Java String indexOf() Method The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

    How do you find the index of a string in a list of strings in Python?

    To find the index of a list element in Python, use the built-in index() method. To find the index of a character in a string, use the index() method on the string. This is the quick answer.