Check if String ends with Specific Word - Regex - Python


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$'

Examples

1. Check if given string ends with the word "cherry"

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 = 'apple banana cherry'
#search using regex
x = re.search('cherry$', str)

if(x!=None):
    print('The line ends with \'cherry\'.')
else:
    print('The line does not end with \'cherry\'.')

Output

The line ends with 'cherry'.

If you print the output of re.search(), x, from the above example, you will get

<re.Match object; span=(13, 19), match='cherry'>

2. Negative scenario

In the following example, we will check if the given string 'apple banana cherry' starts with a specific word 'banana' or not.

Python Program

import re

str = 'apple banana cherry'
#search using regex
x = re.search('banana$', str)

print(x)
if(x!=None):
    print('The line ends with \'banana\'.')
else:
    print('The line does not end with \'banana\'.')

Output

The line does not end with 'banana'.

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.