Python string endswith() example

Python string.endswith() is used to check the end of a string for specific text patterns e.g. domain name extensions and so on.

1. String endswith() method

A simple way to check the end a string is to use the String.endswith().

>>> url = ''

>>> url.endswith('.com')

True		#Output

>>> url.endswith('.net')

false		#Output

2. String endswith() with tuples

If you need to check against multiple choices, simply provide a tuple of strings to endswith().

>>> domains = ["", "", "", ""]

>>> [name for name in domains if name.endswith(('.com', '.org')) ]

['', '']		#Output

>>> any( name.endswith('.net') for name in domains )

True							#Output

3. String endswith() with list or set

To use endswith(), tuple is actually required as input. If you happen to have the choices specified in a list or set, just make sure you convert them using tuple() first.

For example:

>>> choices = ['.com', '.io', '.net']

>>> url = ''

>>> url.endswith(choices)		#ERROR !! TypeError: endswith first arg must be str, unicode, or tuple, not list

>>> url.endswith( tuple(choices) )	#Correct

True							#Output

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment


A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.