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():
s="Python programming"p=s.index("prog")print(p)
7
Explanation: index() method searches for the substring "prog" within "Python programming" and returns starting index7.
s.index(substring, start=0, end=len(s))
Parameters:
Return Type:
Let's understand the use of index() with the help of some examples.
This code demonstrates how to find the index of a substring within a string using the index() method.
s="Python programming is powerful"p=s.index("programming")print(p)
Explanation:
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.
s="Python programming is fun"p=s.index("is",10,25)print(p)
19
Related Articles:Python String find() MethodPython String rindex() MethodPython String rfind() Method
Related Articles:
M
Python Introduction
Input and Output in Python
Python Variables
Python Operators
Python Keywords
Python Data Types
Conditional Statements in Python
Loops in Python - For, While and Nested Loops
Python Functions
Recursion in Python
Python Lambda Functions
Python String
Python Lists
Python Tuples
Python Dictionary
Python Sets
Python Arrays
List Comprehension in Python
Python OOP Concepts
Python Exception Handling
File Handling in Python
Python Database Tutorial
Python MongoDB Tutorial
Python MySQL
Python Packages
Python Modules
Python DSA Libraries
List of Python GUI Library and Packages
NumPy Tutorial - Python Library
Pandas Tutorial
Matplotlib Tutorial
Python Seaborn Tutorial
StatsModel Library - Tutorial
Learning Model Building in Scikit-learn
TensorFlow Tutorial
PyTorch Tutorial
Flask Tutorial
Django Tutorial | Learn Django Framework
Django ORM - Inserting, Updating & Deleting Data
Templating With Jinja2 in Flask
Django Templates
Python | Build a REST API using Flask
How to Create a basic API using Django Rest Framework ?
Python Quiz
Python Coding Practice
Python Interview Questions and Answers