English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
If the string ends with the specified value, the `endswith()` method returns True. If not, it returns False.
The syntax of `endswith()` is:
str.endswith(suffix[, start[, end]])
The `endswith()` function has three parameters:
Suffix -The suffix string or tuple to be checked
Start(Optional)- Check in the stringSuffixStart position.
End(Optional)- Check in the stringSuffixEnd position.
The `endswith()` method returns a boolean value.
Returns True if the string ends with the specified value.
Returns False if the string does not end with the specified value.
text = "Python is easy to learn." result = text.endswith('to learn') # Return False print(result) result = text.endswith('to learn.') # Return True print(result) result = text.endswith('Python is easy to learn.') # Return True print(result)
When running the program, the output is:
False True True
text = "Python programming is easy to learn." # start parameter: 7 # "programming is easy to learn." is the string to be searched result = text.endswith('learn.', 7) print(result) # Pass both start and end parameters # start: 7, end: 26 # "programming is easy" is the string to be searched result = text.endswith('is', 7, 26) # Return False print(result) result = text.endswith('easy', 7, 26) # Return True print(result)
When running the program, the output is:
True False True
You can pass a tuple as a specified value to the endswith() method in Python.
If a string ends with any item in the tuple, endswith() returns True. If not, it returns False
text = "programming is easy" result = text.endswith(('programming', 'python')) # Output False print(result) result = text.endswith(('python', 'easy', 'java')) # Output True print(result) # With start and end parameters # 'programming is' string is checked result = text.endswith(('is', 'an'), 0,) 14) # Output True print(result)
When running the program, the output is:
False True True
If you need to check if a string starts with a specified prefix, you can use it in Pythonstartswith() method.