Python String index Method - Python Tutorial | Logic Practice
Python Course / Other / Python String index Method

Python String index Method

BLUF: This lesson on Python String index Method provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: Python String index Method

Mastering Python String index Method is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

The Python index method functions similarly to the find method, with the distinction that it raises an error when a match is not found. This method provides the index of the first occurrence of a specified substring, and it will trigger an error if no match exists.

Signature

Example

index(sub[, start[, end]])

Parameters

  • sub : substring
  • start : start index a range
  • end : last index of the range
  • Return Type

If the substring is located, it returns the index of that substring; if not, it raises a ValueError.

Let us explore a few examples to gain a better understanding of the index method.

Python String index Method Example 1

Example

# Python index() function example
# Variable declaration
str = "Welcome to our tutorial."
# Calling function
str2 = str.index("at")
# Displaying result
print(str2)

Output:

Python String index Method Example 2

An error is thrown if the substring is not found.

Example

# Python index() function example
# Variable declaration
str = "Welcome to our tutorial."
# Calling function
str2 = str.index("ate")
# Displaying result
print(str2)

Output:

Output

ValueError: substring not found

Python String index Method Example 3

Additionally, we can provide start and end indices as arguments to allow for a more tailored processing experience.

Example

# Python index() function example
# Variable declaration
str = "Welcome to our tutorial."
# Calling function
str2 = str.index("p",19,21)
# Displaying result
print("p is present at :",str2,"index")

Output:

Output

p is present at : 20 index

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience