To check if a string ends with a specific suffix in Python, you can use simple string slicing or the str.endswith()
method.
In this example,
str1
with a string value of "Hello World"
."World"
.True
if the string ends with the specified suffix; otherwise, it returns False
.str1 = 'Hello World'
endsWithWorld = str1[-5:] == 'World'
print(f'String ends with suffix "World": {endsWithWorld}')
String ends with suffix "World": True
In this example,
str2
with a string value of "apple"
.str.endswith()
method with the string object str2
and the suffix "banana"
.str.endswith()
method returns True
if the string ends with the specified suffix; otherwise, it returns False
.str2 = 'apple'
endsWithBanana = str2.endswith('banana')
print(f'String ends with suffix "banana": {endsWithBanana}')
String ends with suffix "banana": False
In this tutorial, we learned How to Check if String ends with Specific Suffix in Python language with well detailed examples.