A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-string-index-applications/ below:

Python String index() Method - GeeksforGeeks

Python String index() Method

Last Updated : 02 May, 2025

The index() method in Python is used to find the position of a specified substring within a given string. It is similar to the find() method but raises a ValueError if the substring is not found, while find() returns -1. This can be helpful when we want to ensure that the substring exists in the string before proceeding. Let's see a simple use of index():

Python
s = "Python programming"

p = s.index("prog")
print(p)

Explanation: index() method searches for the substring "prog" within "Python programming" and returns starting index 7.

Syntax of index()

s.index(substring, start=0, end=len(s))

Parameters:

Return Type:

Example of index() Method

Let's understand the use of index() with the help of some examples.

Example 1: Using index() with only substring argument

This code demonstrates how to find the index of a substring within a string using the index() method.

Python
s = "Python programming is powerful"

p = s.index("programming")
print(p)

Explanation:

Example 2: Using index() with substring, start and end arguments

This code demonstrates how to find the index of a substring within a specific range of a string using the index() method with optional start and end parameters.

Python
s = "Python programming is fun"

p = s.index("is", 10, 25)
print(p)

Explanation:

Related Articles:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4