In this Python tutorial, we will see the index method in Python string, its syntax, the parameters required, and return values. We will see some illustrative examples exploring the functionality of the index() method of Python string.

Python, the popular high-level programming language, provides a plethora of methods for string manipulation, with the index() method being one of the most useful.

The index method in Python string

The index() method in Python is a string method that is used to find the position of a substring within a string. If the Python substring exists, it returns the lowest index of its occurrence and raises an exception if the specified value is not found.

Syntax:

The syntax of the Python string index() method is:

str.index(sub, start, end)

Here, str is the string on which the operation is going to be held.

Parameters:

  • sub- The substring that needs to be found.
  • start(optional)- The start index where the search should begin within the Python string.
  • end(optional)- The end index where the search should end within the Python string.

Return values:

  • If the substring exists inside the Python string, it returns the lowest index in the Python string where the substring is found.
  • If the substring doesn’t exist inside the Python string, it raises a ValueError exception.

Python string index() function examples

There can be many different ways to use the Python index() function in the string. Let’s see them one by one:

Example-1: The basic Python index() function

To find the position of a substring in a Python string we can use the index function in Python.

For example, Imagine we’re a tourist guide, and we have a sentence about the USA’s geography and we want to locate where the mention of a particular landmark or place is in the sentence.

sentence = "The USA has the Grand Canyon in Arizona," 
           "Mount Rushmore in South Dakota, " 
           "and the Statue of Liberty in New York."

position = sentence.index("Statue of Liberty")

print(f"The phrase 'Statue of Liberty' starts at position position.")

The output is:

When we run the code, the index() method searches the sentence Python string for the substring “Statue of Liberty”. Upon finding it, the method returns the position (or index) where this substring begins.

The phrase 'Statue of Liberty' starts at position 80.

This way we can use the index string method in Python to find the location of a substring within a Python string.

Example-2: The Python string index method with start and end parameters

We can also start our search within a range, for that we need to provide a start and an end parameters.

For instance, Imagine we’re analyzing data about US presidents, and we have a Python string with the names of some of them in sequence. If we want to find the second occurrence of “John Adams”, we can use the start and end parameters:

presidents = "George Washington John Adams Thomas Jefferson John Adams Joe Biden Donald Trump"

first_occurrence = presidents.index("John Adams")

second_occurrence = presidents.index("John Adams", first_occurrence + 1, 60)

print(second_occurrence)

The output is:

46
Python index string method with start and end parameter

Note: if we extend the end range beyond “John Adams” the output will remain the same.

This way we can find the position of a substring within a range in a Python string using Index() method.

Example-3: The index() method with substring out of range in Python string.

Since the index() method raises a ValueError exception if the substring is not found in the given Python string, we should handle this exception using a try-except block.

For example, let’s search for a city that is not in our string:

cities = "New York, Los Angeles, Chicago, Houston, Miami"

position = cities.index("Seattle")

print('Position')

The output is:

Traceback (most recent call last):
  File "C:UsersUSERPycharmProjectspythonProjectTSmain.py", line 3, in <module>
    position = cities.index("Seattle")
               ^^^^^^^^^^^^^^^^^^^^^^^
ValueError: substring not found
The index python string method with exception

This can be handled by using the try/except block in Python.

cities = "New York, Los Angeles, Chicago, Houston, Miami"

try:
    position = cities.index("Seattle")
except ValueError:
    print("City not found in the string.")

The output will be:

City not found in the string.
Python index method in string with error handling

This way we can handle the exception in the index() method in string Python.

How index() method is different from find() method in Python string

Both the index() and find() methods in Python strings are used to locate the position of a substring within a larger string. However, there are key differences in their behavior when the substring is not found in the string.

Return Value on Failure:

  • index(): If the specified substring is not found, the index() method raises a ValueError.
  • find(): If the specified substring is not found, the find() method returns -1.

Conclusion

The index() method in Python string is a powerful tool for searching within strings. By understanding how to use the start and end parameters, and how to handle exceptions, we can efficiently find substrings within larger texts.

We have also seen some different examples of how different parameters within the index function can lead to different functionality of the index method in Python and how the index method is different from the find method in Python.

You may also like to read:



Source link

Leave a Reply

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

I wanted to again thank you for your help in selling my condominium at coconut point. Bildungsressourcen in sozialen netzwerken. La06 central lehigh acres.