Check if String ends with a Substring using Regex in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
6 min

banner

# Table of Contents

  1. Check if string ends with a substring using Regex in Python
  2. Check if a string ends with a Number in Python
  3. Using endswith() with multiple strings in Python

# Check if string ends with a substring using Regex in Python

Use the re.search() method to check if a string ends with a substring using a regular expression, e.g. re.search(r'\d$', string).

The dollar sign $ is used to only match the regular expression at the end of the string.

main.py
import re string = 'bobbyhadz.com' match = re.search(r'\.com$', string) print(match) # ๐Ÿ‘‰๏ธ <re.Match object; span=(9, 13), match='.com'> if match is not None: print('The string ends with the regex') print(match.group()) # ๐Ÿ‘‰๏ธ .com print(match.start()) # ๐Ÿ‘‰๏ธ 9 else: print('The string does NOT end with the regex')

check if string ends with substring using regex

The code for this article is available on GitHub

If you need to check if a string ends with a substring ignoring the case, use the re.IGNORECASE flag.

main.py
import re string = 'BOBBYHADZ.COM' match = re.search(r'\.com$', string, flags=re.IGNORECASE) print(match) # ๐Ÿ‘‰๏ธ <re.Match object; span=(9, 13), match='.COM'>

The first example uses the re.search() method to check if a string ends with a substring using a regular expression.

The re.search() method looks for the first location in the string where the provided regular expression produces a match.

main.py
import re # ๐Ÿ‘‡๏ธ <re.Match object; span=(5, 6), match='3'> print(re.search(r'\d$', 'abc123')) # ๐Ÿ‘‡๏ธ None print(re.search(r'\d$', '123abc'))
If the re.search() method finds a match, it will return a match object, otherwise None is returned.

The first argument we passed to the re.search() method is a regular expression.

The dollar sign $ matches the end of the string, so the re.search() method only looks for a match at the end.

If you need to get the match and the index of the match in the string, use the match.group() and match.start() methods.

main.py
import re string = 'bobbyhadz.com' match = re.search(r'\.com$', string) if match is not None: print('The string ends with the regex') print(match.group()) # ๐Ÿ‘‰๏ธ .com print(match.start()) # ๐Ÿ‘‰๏ธ 9 else: print('The string does NOT end with the regex')

If you ever need help reading or writing a regular expression, consult the regular expression syntax subheading in the official docs.

The page contains a list of all of the special characters with many useful examples.

# Checking if a string ends with a substring using endswith()

You can also use the str.endswith() method to check if a string ends with a substring. The method can be passed a string or a tuple of strings.

main.py
string = 'bobbyhadz.com' print(string.endswith('.com')) # ๐Ÿ‘‰๏ธ True # ๐Ÿ‘‡๏ธ True print(string.endswith(('.abc', '.xyz', '.com')))

checking if string ends with substring using endswith

The code for this article is available on GitHub

The str.endswith() method returns True if the string ends with the provided suffix, otherwise the method returns False.

If you pass a tuple to the endswith() method, it checks if the string ends with any of the strings in the tuple.

However, the str.endswith() method doesn't support regular expressions.

# Check if a string ends with a Number in Python

Use the re.search() method if you need to check if a string ends with a number.

main.py
import re string = 'bobby246' match = re.search(r'\d+$', string) if match is not None: print('The string ends with a number') print(match.group()) # ๐Ÿ‘‰๏ธ '246' print(int(match.group())) # ๐Ÿ‘‰๏ธ 246 print(match.start()) # ๐Ÿ‘‰๏ธ 5 else: print('The string does NOT end with a number')

check if string ends with number

The code for this article is available on GitHub
If you're looking for a non-regex solution, scroll down to the next subheading.

The re.search() method looks for the first location in the string where the provided regular expression produces a match.

main.py
import re string = 'bobby246' match = re.search(r'\d+$', string) # ๐Ÿ‘‡๏ธ <re.Match object; span=(5, 8), match='246'> print(match) # ๐Ÿ‘‡๏ธ None print(re.search(r'\d+$', 'abc'))
If the re.search() method finds a match, it will return a match object, otherwise None is returned.

The first argument we passed to the re.search() method is a regular expression.

The \d character matches the digits [0-9] (and many other digit characters).

The plus + causes the regular expression to match 1 or more repetitions of the preceding character (the digit).

The dollar sign $ matches the end of the string.

In its entirety, the regular expression matches one or more digits at the end of the string.

You can use the match.group() method if you need to get the number that is at the end of the string.

main.py
import re string = 'bobby246' match = re.search(r'\d+$', string) if match is not None: print('The string ends with a number') print(match.group()) # ๐Ÿ‘‰๏ธ '246' print(int(match.group())) # ๐Ÿ‘‰๏ธ 246 print(match.start()) # ๐Ÿ‘‰๏ธ 5 else: print('The string does NOT end with a number')
The code for this article is available on GitHub

The match.group() method returns the matched number as a string. You can use the int() class if you need to convert the string to an integer.

Make sure to use an if statement before calling the match.group() method. The re.search() method would return None if the string doesn't end with a number.

The match.start() method returns the index of the first digit of the match.

# Check if a string ends with a Number using str.isdigit()

This is a three-step process:

  1. Access the string at index -1 to get the last character.
  2. Call the str.isdigit() method on the character.
  3. If the method returns True, the string ends with a number.
main.py
string = 'bobby246' if string and string[-1].isdigit(): # ๐Ÿ‘‡๏ธ this runs print('The string ends with a number') else: print('The string does NOT end with a number')
The code for this article is available on GitHub

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

main.py
string = 'bobby246' print(string[-1]) # ๐Ÿ‘‰๏ธ 6
Negative indices can be used to count backward, e.g. string[-1] returns the last character in the string and string[-2] returns the second to last character.

We got the last character of the string and used the str.isdigit() method to check if it's a digit.

The str.isdigit() method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

main.py
print('A'.isdigit()) # ๐Ÿ‘‰๏ธ False print('5'.isdigit()) # ๐Ÿ‘‰๏ธ True

We also used the boolean and operator to make sure the string isn't empty.

main.py
string = 'bobby246' if string and string[-1].isdigit(): # ๐Ÿ‘‡๏ธ this runs print('The string ends with a number') else: print('The string does NOT end with a number')

The part to the right of the boolean and operator isn't evaluated if the string is empty.

This is important because accessing an empty string at an index raises an IndexError exception.

# Using endswith() with multiple strings in Python

You can pass a tuple to the endswith() method to use it with multiple strings.

The method can be passed a tuple of suffixes and returns True if the string ends with any of the suffixes in the tuple.

main.py
my_str = 'bobbyhadz.com' if my_str.endswith(('com', 'org', 'net')): # ๐Ÿ‘‡๏ธ this runs print('The string ends with one of the suffixes') else: print('The string does NOT end with any of the suffixes') print(my_str.endswith(('com', 'org', 'net'))) # ๐Ÿ‘‰๏ธ True print(my_str.endswith(('a', 'b', 'c'))) # ๐Ÿ‘‰๏ธ False
The code for this article is available on GitHub

The str.endswith() method returns True if the string ends with the provided suffix, otherwise the method returns False.

main.py
my_str = 'bobbyhadz.com' print(my_str.endswith('com')) # ๐Ÿ‘‰๏ธ True print(my_str.endswith('abc')) # ๐Ÿ‘‰๏ธ False

The str.endswith() method can also be passed a tuple of suffixes and returns True if the string ends with any of the suffixes.

main.py
my_str = 'bobbyhadz.com' print(my_str.endswith(('com', 'org', 'net'))) # ๐Ÿ‘‰๏ธ True print(my_str.endswith(('a', 'b', 'c'))) # ๐Ÿ‘‰๏ธ False

Having two sets of parentheses next to one another might be a bit difficult to read, so you can extract the tuple into a variable.

main.py
my_str = 'bobbyhadz.com' suffixes = ('com', 'org', 'net') if my_str.endswith(suffixes): # ๐Ÿ‘‡๏ธ this runs print('The string ends with one of the suffixes') else: print('The string does NOT end with any of the suffixes') print(my_str.endswith(suffixes)) # ๐Ÿ‘‰๏ธ True

If the string ends with any of the suffixes, the str.endswith() method returns True, otherwise False is returned.

# Using any() with a generator expression

An alternative and more verbose approach is to use the any() function with a generator expression.

main.py
my_str = 'bobbyhadz.com' suffixes = ('com', 'org', 'net') if any(my_str.endswith(suffix) for suffix in suffixes): # ๐Ÿ‘‡๏ธ this runs print('The string ends with one of the suffixes') else: print('The string does NOT end with any of the suffixes')
The code for this article is available on GitHub

We used a generator expression in the call to any().

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we call the str.endswith() method with the current suffix and return the result.

The any function takes an iterable as an argument and returns True if any element in the iterable is truthy.

If the iterable is empty or none of the elements in the iterable are truthy, the any function returns False.

If the condition is met at least once, the any() function short-circuits and returns True.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev