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!
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()
This doesn't account for anything in the middle of the string, but it basically says that if the last number is a digit, it ends with a number.
In : s = "hello123" In : s[-1].isdigit() Out: True
With a few strings:
In : for s in ['hello12324', 'hello', 'hello1345252525', 'goodbye']: ...: print s, s[-1].isdigit() ...: hello12324 True hello False hello1345252525 True goodbye False
I fully and completely support the regex solution(s), but here is one (not pretty) way you could get the number. Again, regex is much better here :)
In : from itertools import takewhile In : s = '12hello123558' In : r = s[-1::-1] In : d = [c.isdigit() for c in r] In : ''.join((i for i in takewhile(lambda (x, y): y, zip(r, d))))[-1::-1] Out: '123558'
This one will simply return an empty string if the string ends with something that is not a number.
import re re.split('[^\d]', str)[-1]
Since an empty string is falsy, you can overload the meaning:
def getNumericTail(str): re.split('[^\d]', str)[-1] def endsWithNumber(str): bool(getNumericTail(str))
a = "abc1323" b = "" for c in a[::-1]: try: b += str(int(c)) except: break print b[::-1]