How to Find Last Number in String in Python
Published on Aug. 22, 2023, 12:16 p.m.
To find the last number in a string in Python, you can use regular expressions. Here’s an example implementation:
import re
my_string = "Hello world 47"
match = re.search('\d+$', my_string)
if match:
last_number = match.group()
print(last_number)
else:
print("No number found")
In this example, the \d
pattern matches any digit, and the +
qualifier matches one or more consecutive digits. The $
matches the end of the string. The code then prints the last number found in the string as a string (in this case, “47”).
Note that this implementation assumes that the number you’re looking for only contains digits. If there are other characters in the number, you’ll need to modify the regular expression accordingly. Also, if there is no number in the string, the code prints “No number found”.