Python string index() method

Python String index() Method

Description

The index() method is used to determine whether a given substring occurs within a string or part of a string, given a starting index beg and an ending index end. This method is identical to the find() method, but raises a ValueError exception if the substring is not found.

Syntax

Following is the syntax of the index() method –

var.index(sub, beg=0, end=len(string))

Parameters

  • sub – This specifies the string to be searched.
  • beg – This is the starting index, which defaults to 0.
  • end – This is the ending index, which defaults to the length of the string.

Return Value

Returns the index where the substring is found, otherwise raises a ValueError.

Example

var = "Explicit is better than implicit."

var1 = var.index('i')
print("Original string:", var)
print("Index of character 'i':", var1)

var2 = var.index('z')
print("Index of character 'z':", var2)

When you run this program, it will produce the following output –

Original string: Explicit is better than implicit.
Index of character 'i': 4
Traceback (most recent call last):
File "C:Usersmlathexamplesmain.py", line 7, in <module>
var2 = var.index('z')
^^^^^^^^^^^^^^^
ValueError: substring not found

The program raises a ValueError because the letter x does not exist in the string after the 10th index.

Leave a Reply

Your email address will not be published. Required fields are marked *