Last updated: Apr 10, 2024
Reading timeยท6 min
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.
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')
If you need to check if a string ends with a substring ignoring the case, use
the re.IGNORECASE
flag.
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.
import re # ๐๏ธ <re.Match object; span=(5, 6), match='3'> print(re.search(r'\d$', 'abc123')) # ๐๏ธ None print(re.search(r'\d$', '123abc'))
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.
$
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.
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.
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.
string = 'bobbyhadz.com' print(string.endswith('.com')) # ๐๏ธ True # ๐๏ธ True print(string.endswith(('.abc', '.xyz', '.com')))
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.
Use the re.search()
method if you need to check if a string ends with a
number.
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 re.search() method looks for the first location in the string where the provided regular expression produces a match.
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'))
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).
+
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.
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 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.
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.
This is a three-step process:
-1
to get the last character.str.isdigit()
method on the character.True
, the string ends with a number.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')
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
.
string = 'bobby246' print(string[-1]) # ๐๏ธ 6
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.
print('A'.isdigit()) # ๐๏ธ False print('5'.isdigit()) # ๐๏ธ True
We also used the boolean and
operator to make sure the string isn't empty.
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.
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.
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
str.endswith()
method returns True
if the string ends with the provided suffix, otherwise the
method returns False
.
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.
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.
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.
An alternative and more verbose approach is to use the any()
function with a
generator expression.
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')
We used a generator expression in the call to any()
.
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
.
You can learn more about the related topics by checking out the following tutorials: