Python – Check if the last characters in a string are numbers
Question:
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!
Answers:
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 [4]: s = "hello123"
In [5]: s[-1].isdigit()
Out[5]: True
With a few strings:
In [7]: 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 [43]: from itertools import takewhile
In [44]: s = '12hello123558'
In [45]: r = s[-1::-1]
In [46]: d = [c.isdigit() for c in r]
In [47]: ''.join((i[0] for i in takewhile(lambda (x, y): y, zip(r, d))))[-1::-1]
Out[47]: '123558'
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.
another solution:
a = "abc1323"
b = ""
for c in a[::-1]:
try:
b += str(int(c))
except:
break
print b[::-1]
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))
Another solution: see how many 0-9 digits you can strip of the end of string and use that length as an index into string to split of the number.
(Returns ''
in case string does not end in a number).
In [1]: s = '12hello123558'
In [2]: s[len(s.rstrip('0123456789')):]
Out[2]: '123558'
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!
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 [4]: s = "hello123"
In [5]: s[-1].isdigit()
Out[5]: True
With a few strings:
In [7]: 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 [43]: from itertools import takewhile
In [44]: s = '12hello123558'
In [45]: r = s[-1::-1]
In [46]: d = [c.isdigit() for c in r]
In [47]: ''.join((i[0] for i in takewhile(lambda (x, y): y, zip(r, d))))[-1::-1]
Out[47]: '123558'
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.
another solution:
a = "abc1323"
b = ""
for c in a[::-1]:
try:
b += str(int(c))
except:
break
print b[::-1]
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))
Another solution: see how many 0-9 digits you can strip of the end of string and use that length as an index into string to split of the number.
(Returns ''
in case string does not end in a number).
In [1]: s = '12hello123558'
In [2]: s[len(s.rstrip('0123456789')):]
Out[2]: '123558'