Python String rindex() Method
The Python rindex() method is a string method that finds the last occurrence of a specified value in a string. It has the following syntax:
string.rindex(value, start, end)
where value is the substring to be searched for, start and end are optional parameters that specify the range of indexes to search within (default is the whole string).
The rindex() method returns an integer value that represents the highest index where value is found. If value is not found, it raises a ValueError exception.
Here are some examples of using the Python rindex() method:
# Example 1: Find the last occurrence of 'l' in 'Hello World'
greet = 'Hello World'
index = greet.rindex('l')
print(index)
# Output: 9
# Example 2: Find the last occurrence of 'tutorials' in a sentence
mystr = 'tutorialsteacher is a free tutorials website'
index = mystr.rindex('tutorials')
print(index)
# Output: 25
# Example 3: Find the last occurrence of 'o' between index 0 and 5
greet = 'Hello World'
index = greet.rindex('o', 0, 5)
print(index)
# Output: 4
# Example 4: Try to find a substring that does not exist
mystr = 'Python programming'
try:
index = mystr.rindex('Java')
print(index)
except ValueError as e:
print(e)
# Output: substring not found
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment