Python - Check if string ends with a specific suffix


Python - Check if string ends with a specific suffix

To check if a string ends with a specific suffix string in Python, we can use str.endswith() function, or use regular expression.

In this tutorial, we shall see the two approaches of using str.endswith() function, or a regular expression, to check if given string ends with a specific substring or value.

Examples

1. Check if given string ends with a specific word using str.endswith() function

In this example, we will check if the given string "Hello World" ends with the specific word "World" or not using string endswith() function.

Python Program

my_string = "Hello, World!"
suffix_to_check = "World!"

if my_string.endswith(suffix_to_check):
    print('Given string ends with specified suffix.')
else:
    print('Given string does NOT end with specified suffix.')

Output

Given string ends with specified suffix.

2. Check if given string ends with a specific word using regular expression

In this example, we will check if the given string "Hello World" ends with the specific word "World" or not using search() function of re module.

We shall use re.escape() to escape any special characters in the suffix and then construct a regular expression pattern to match the end of the string ("$" signifies the end of the string).

Python Program

import re

my_string = "Hello, World!"
suffix_to_check = "World!"
pattern = re.escape(suffix_to_check) + "$"

if bool(re.search(pattern, my_string)):
    print('Given string ends with specified suffix.')
else:
    print('Given string does NOT end with specified suffix.')

Output

Given string ends with specified suffix.

You may take another value for suffix string suffix_to_check, and check the output.

Summary

In this tutorial, we learned how to check if a string ends with a substring or word using string endswith() function, or Python Regular Expressions.