
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to check whether a string ends with one from a list of suffixes in Python?
Python has a method endswith(tuple) in the String class. This method accepts a tuple of strings that you want to search and is called on a string object. You can call this method in the following way:
string = 'core java' print(string.endswith(('txt', 'xml', 'java', 'orld')))
OUTPUT
True
There is another way to find if a string ends with a given list of suffixes. You can use re.search from the re module(regular expression) to do so. Regex interprets $ as end of line. We also need to seperate out the suffixes using grouping and | symbol in regex. For example,
import re string = 'core java' print(bool(re.search('(java|xml|py|orld)$', string))) print(bool(re.search('(java|xml|py|orld)$', 'core java'))) print(bool(re.search('(java|xml|py)$', 'Hello world')))
OUTPUT
True True False
re.search returns an object, to check if it exists or not, we need to convert it to a boolean using bool(). You can read more about Python regex here.
- Related Articles
- Check whether a string ends with some other string - JavaScript
- How to check if string or a substring of string ends with suffix in Python?
- Python - Check whether a string starts and ends with the same character or not
- How to check whether a string starts with XYZ in Python?
- How to check if a string ends with a specified Suffix string in Golang?
- Python Program to check whether all elements in a string list are numeric
- Check if a string ends with given word in PHP
- Java Program to check whether one String is a rotation of another.
- How to check if the string ends with specific substring in Java?
- How to Check Whether a String is Palindrome or Not using Python?
- Check whether second string can be formed from characters of first string in Python
- How do we check in Python whether a string contains only numbers?
- JavaScript Check whether string1 ends with strings2 or not
- How to check whether a string contains a substring in JavaScript?
- How to check whether a string contains a substring in jQuery?

Advertisements