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

 ̄綄美尐妖づ 提交于 2019-12-02 23:27:24
Peter Graham
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.

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'

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'

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:

a = "abc1323"
b = ""
for c in a[::-1]:
    try:
        b += str(int(c))
    except: 
        break

print b[::-1]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!