user2002290 user2002290 - 14 days ago 6
Python Question

Python - Check if the last characters in a string are numbers

Basically I want to know how I would do this.

Here's an example string:

string = "hello123"


I would like to know how I would check if the string ends in a number, then print the number the string ends in.

I know for this certain string you could use regex to determine if it ends with a number then use string[:] to select "123". BUT if I am looping through a file with strings like this:

hello123
hello12324
hello12435436346


...Then I will be unable to select the number using string[:] due to differentiation in the number lengths. I hope I explained what I need clearly enough for you guys to help. Thanks!

Answer
import re
m = re.search(r'\d+$', string)
# if the string ends in digits m will be a Match object, or None otherwise.
if m is not None:
    print m.group()

\d matches a numerical digit, \d+ means match one-or-more digits (greedy: match as many consecutive as possible). And $ means match the end of the string.