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 = 'https://howtodoinjava.com'

>>> 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 = ["example.io", "example.com", "example.net", "example.org"]

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

['example.com', 'example.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 = 'https://howtodoinjava.com'

>>> 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 !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode