HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Python / Python string endswith() example

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

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Python Inbuilt Functions

  • Python abs()
  • Python all()
  • Python any()
  • Python ascii()
  • Python bin()
  • Python input()
  • Python print()

Python String Functions

  • Python String endswith()
  • Python String split()
  • Python String startswith()

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces