String endswith() in Python

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to learn about the endswith() method of the string.

The method endswith() will return True if the string ends with given substring or else it will False. It takes one required argument and two optional arguments.

The required argument is a string that needs to be checked and optional arguments are and they are start and end indexes. By default, the start index is 0 and the end index is length -1.

Example

 Live Demo

# initializing a string
string = "tutorialspoint"
# checking for 'point'
print(string.endswith('point'))
# checking for 'Point'
print(string.endswith('Point'))
# checking for 'tutorialspoint'
print(string.endswith('tutorialspoint'))

Output

If you run the above code, then you will get the following result.

True
False
True

If we provide the start and end indexes then the endswith() will check the string in between those indexes. The method doesn't include the last end index. Let's see an example.

Example

 Live Demo

# initializing a string
string = "tutorialspoint"
# checking for 'point'
print(string.endswith('point', 10, len(string)))
# checking for 'Point'
print(string.endswith('point', 8, len(string)))
# checking for 'tutorialspoint'
print(string.endswith('tutorialspoint', 0, len(string) - 1))

Output

If you run the above code, then you will get the following result.

False
True
False

Conclusion

If you have any doubts regarding the tutorial, mention them in the comment section.

raja
Published on 11-Jul-2020 07:12:43
Advertisements