Skip to content
Related Articles

Related Articles

Python String endswith() Method

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 08 Jun, 2022

Python String endswith() method returns True if a string ends with the given suffix otherwise returns False.

Syntax:

str.endswith(suffix, start, end)

Parameters: 

  • suffix: Suffix is nothing but a string that needs to be checked. 
  • start: Starting position from where suffix is needed to be checked within the string. 
  • end: Ending position + 1 from where suffix is needed to be checked within the string.  

Note: If start and end index is not provided then by default it takes 0 and length -1 as starting and ending indexes where ending index is not included in our search.

Returns: 
It returns True if the string ends with the given suffix otherwise return False. 

Example 1: Working of endswith() method Without start and end Parameters

In example 1 we shall look at multiple test cases on how one can use endswith() method without start and end parameters. 

Syntax:

var = string_value
var.endswith("ending_needs_to_checked")

Note: ending_needs_to_be_checked can be edited into anything, check the below examples. 

Example 1:

Python




# Python code shows the working of
# .endswith() function
 
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

Example 2: Working of endswith() method With start and end Parameters

In example 2 we shall add two extra parameters, the reason to add start and the 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. 

Python




# Python code shows the working of
# .endswith() function
 
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
True
False 

Real-World Example where endswith() is widely used

Python3




print("***Valid Geeksforgeeks Email Checker***\n")
user_email = input("Enter your GFG Official Mail:").lower()
if user_email.endswith("@geeksforgeeks.org"):
    print("Hello Geek")
else:
    print("Invalid, A Stranger detected")


Output:

***Valid Geeksforgeeks Email Checker***

Enter your GFG Official Mail:sandeepjain@geeksforgeeks.org
Hello Geek


***Valid Geeksforgeeks Email Checker***

Enter your GFG Official Mail:sandeepjain@google.com
Invalid, A Stranger detected


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!