Contents
Python Regex – Check if String ends with Specific Word
To check if a string ends with a word in Python, use the regular expression for “ends with” $ and the word itself before $. We will use re.search() function to do an expression match against the string.
The Regular Expression to check if string ends with the word is as shown in the following.
'theword$'
Example 1: Check if String ends with a Word
In the following example, we will check if the given string Python is a programming language ends with a specific word language or not.
Python Program
import re
str = 'Python is a programming language'
#search using regex
x = re.search('language$', str)
if(x!=None):
print('The line ends with \'language\'.')
else:
print('The line does not end with \'language\'.')
Run Output
The line ends with 'language'.
If you print the output of re.search(), x, from the above example, you will get
<re.Match object; span=(24, 32), match='language'>
Example 2: Check if String ends with a Word
In the following example, we will check if the given string Python is a programming language. starts with a specific word programming or not.
Python Program
import re
str = 'Python is a programming language'
#search using regex
x = re.search('programming$', str)
if(x!=None):
print('The line ends with \'programming\'.')
else:
print('The line does not end with \'programming\'.')
Run Output
The line does not end with 'programming'.
If you print the output of re.search(), x, from the above example, you will get
None
If there are no matching instances for the regular expression provided, you will get None as output for re.search() function.
Summary
In this tutorial of Python Examples, we learned how to check if a string ends with a substring or word, using Python Regular Expressions, with the help of well illustrated examples.