Movatterモバイル変換


[0]ホーム

URL:


Open In App

The index()method in Python is used to find the position of a specified substring within a given string. It is similar to thefind() method but raises aValueError if the substring is not found, whilefind() 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 ofindex():

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

Output
7

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

Syntax of index()

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

Parameters:

  • substring:The substring to locate within the strings.
  • start (optional):The starting index for the search. Defaults to0 if not provided.
  • end (optional): The ending index for the search. If not provided, it defaults to the length of the string.

Return Type:

  • Returns the lowest index of the substring if found in the given string.
  • Raises aValueError if the substring is not found in the specified range.

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)

Output
7

Explanation:

  • Here, we only provide the substring argument "programming".
  • index() searches from the start of the string and finds "programming" at index 7, which it returns.

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)

Output
19

Explanation:

  • We specify start=10andend=25, soindex() searches between these positions.
  • It finds "is" at index18 within this range and returns18.

Related Articles:


Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp