Python String endswith() Method Example
string = "w3wiki"
print(string.endswith("geeks"))
Output
True
Python endswith() without start and end Parameters
we shall look at multiple test cases on how one can use Python String endswith() method without start and end parameters.
text = "geeks for geeks."
# returns False
result = text.endswith('for geeks')
print (result)
# returns True
result = text.endswith('geeks.')
print (result)
# returns True
result = text.endswith('for geeks.')
print (result)
# returns True
result = text.endswith('geeks for geeks.')
print (result)
Output
False True True True
Time complexity: O(n), where n is the length of the string being searched for.
Auxiliary space: O(1), as the method endswith() only requires a constant amount of memory to store the variables text, result, and the string being searched for.
Python endswith() With start and end Parameters
we shall add two extra parameters, the reason to add start and end values is that sometimes you need to provide big suffix/text to be checked and that time start and end parameters are very important.
text = "geeks for geeks."
# start parameter: 10
result = text.endswith('geeks.', 10)
print(result)
# Both start and end is provided
# start: 10, end: 16 - 1
# Returns False
result = text.endswith('geeks', 10, 16)
print(result)
# returns True
result = text.endswith('geeks', 10, 15)
print(result)
Output
True False True
Real-World Example where endswith() is widely used
In this example, we take a String input from the user and check whether the input String endswith ‘@w3wiki.org’ or not, then we print ‘Hello Geek’ else we print ‘Invalid, A Stranger detected’.
print("***Valid w3wiki Email Checker***\n")
user_email = input("Enter your GFG Official Mail:").lower()
if user_email.endswith("@w3wiki.org"):
print("Hello Geek")
else:
print("Invalid, A Stranger detected")
Output:
***Valid w3wiki Email Checker***
Enter your GFG Official Mail:s@w3wiki.org
Hello Geek
***Valid w3wiki Email Checker***
Enter your GFG Official Mail:s@google.com
Invalid, A Stranger detected
Python String endswith() Method
Python String endswith() method returns True if a string ends with the given suffix, otherwise returns False.