
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to check if string or a substring of string ends with suffix in Python?
Python has a method endswith(string) in the String class. This method accepts a suffix string that you want to search and is called on a string object. You can call this method in the following way:
string = 'C:/Users/TutorialsPoint1/~.py' print(string.endswith('.py'))
OUTPUT
True
There is another way to find if a string ends with a given suffix. You can use re.search(suffix + '$', string) from the re module(regular expression) to do so. Regex interprets $ as end of line, so if you want to search for a suffix, you need to do the following:
string = 'C:/Users/TutorialsPoint1/~.py' import re print(bool(re.search('py$', string)))
OUTPUT
True
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 <a href="https://docs.python.org/2/library/re.html" target="_blank">here</a>.
- Related Questions & Answers
- How to check if a string ends with a specified Suffix string in Golang?
- How to check if string or a substring of string starts with substring in Python?
- How to check if the string ends with specific substring in Java?
- How to determine if an input string ends with a specified suffix in JSP?
- Check if a string is suffix of another in Python
- Check if a string ends with given word in PHP
- Python Check if suffix matches with any string in given list?
- Check if string ends with desired character in JavaScript
- Check if suffix and prefix of a string are palindromes in Python
- Check if substring present in string in Python
- Check whether a string ends with some other string - JavaScript
- Python Program to check if a string starts with a substring using regex
- How to check if a string contains a substring in Golang?
- Python - Check whether a string starts and ends with the same character or not
- How to check if a substring is contained in another string in Python
Advertisements