Friday, December 27, 2024
Google search engine
HomeLanguagesPython String index() Method

Python String index() Method

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

Python String Index() Method Syntax

Syntax:  string_obj.index(substring, start, end)

Parameters: 

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

Return:  Returns the first position of the substring found.

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

Python String Index() Method Example

Here the first character of ‘and’ in string random is ‘a’ and the index of ‘a’ is 1, so the output is also 1.

Python3




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


Output

Index of 'and' in string: 1 

Python String Index() Method for Finding Index of Single Character

Basic usage of the Python string index() method is to the index position of a particular character or it may be a word. So whenever we need to find the index of a particular character we use the index method to get it.

Python3




# initializing target string 
ch = "neveropen"
  
# initializing argument string 
ch1 = "Lazyroar"
  
# using index() to find position of "Lazyroar"
# starting from 2nd index 
# prints 8
pos = ch.index(ch1,2)
  
print("The first position of Lazyroar after 2nd index : ",end="")
print(pos)


Output

The first position of Lazyroar 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.

Python String Index() with Start and End Arguments

The index() method in Python is used to find the index of the first occurrence of a substring within a string. It returns the index of the substring if found, and raises a ValueError if the substring is not present.

Python3




test_string = "1234gfg4321"
# finding gfg in string segment 'gfg4'
print(test_string.index('gfg', 4, 8))
  
# finding "21" in string segment 'gfg4321'
print(test_string.index("21", 8, len(test_string)))
  
# finding "32" in string segment 'fg432' using negative index
print(test_string.index("32", 5, -1))


Output

4
9
8

Python String Index() Method using List Comprehension

The index() method in Python is used to find the index of the first occurrence of a substring within a string. This example uses list comprehension to find the indices of multiple substrings in the string.

Python3




text = "Hello Geeks and welcome to GeeksforLazyroar"
substring_list = ["Geeks", "welcome", "notfound"]
  
indices = [text.index(sub) if sub in text else -1 for sub in substring_list]
print(indices)  


Output

[6, 16, -1]

Python String Index() Method using Tuple

The index() method in Python is used to find the index of the first occurrence of a substring within a string. The index() method can be used with a tuple to find the index of the first occurrence of any substring from the tuple within the given string.

Python3




text = "Hello Geeks! and welcome to GeeksforLazyroar"
substring_tuple = ("Geeks", "to", "!", "notfound")
  
for sub in substring_tuple:
    try:
        index = text.index(sub)
        print(f"Index of '{sub}': {index}")
    except ValueError as e:
        print(f"Substring '{sub}' not found!")


Output

Index of 'Geeks': 6
Index of 'to': 25
Index of '!': 11
Substring 'notfound' not found!

Exception when using Python String index() Method

Sometimes we got some exceptions that lead to some error in the case of the index() we have here an error also named Value Error.

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

Python




# initializing target string 
ch = "neveropen"
  
# initializing argument string 
ch1 = "gfg"
  
# using index() to find position of "gfg"
# raises error
pos = ch.index(ch1)
  
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(ch1)
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




# initializing target strings
VOLTAGES = ["001101 AC", "0011100 DC", "0011100 AC", "001 DC"]
  
# initializing argument string
TYPE = "AC"
  
# initializing bit-length calculator
SUM_BITS = 0
  
for i in VOLTAGES:
  
    ch = i
  
    if ch[len(ch) - 2] != "D":
        # extracts the length of bits in string
        bit_len = ch.index(TYPE) - 1
  
        # adds to total
        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

RELATED ARTICLES

Most Popular

Recent Comments