user2002290 user2002290 - 1 year ago 122
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:


...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 Source
import re
m ='\d+$', string)
# if the string ends in digits m will be a Match object, or None otherwise.
if m is not None:

\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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download