Python - 检查字符串最后的字符是否为数字

51 投票
5 回答
84170 浏览
提问于 2025-04-17 13:23

基本上,我想知道我该怎么做。

这里有一个示例字符串:

string = "hello123"

我想知道如何检查这个字符串是否以数字结尾,然后打印出这个字符串结尾的数字。

我知道对于这个特定的字符串,你可以用正则表达式来判断它是否以数字结尾,然后用字符串切片(string[:])来选择“123”。但是,如果我在处理一个包含这样的字符串的文件时:

hello123
hello12324
hello12435436346

...那么由于数字长度不同,我就无法使用字符串切片(string[:])来选择数字。我希望我能清楚地解释我需要的内容,以便你们能帮我。谢谢!

5 个回答

8

另一种解决方案是:看看你能从 string 的末尾去掉多少个 0-9 的数字,然后用这个长度作为索引来从 string 中分割出这个数字。
(如果 string 的末尾没有数字,这个方法会返回 '')。

In [1]: s = '12hello123558'

In [2]: s[len(s.rstrip('0123456789')):]
Out[2]: '123558'
44

这段话没有考虑到字符串中间的内容,但基本上是说如果最后一个字符是数字,那这个字符串就是以数字结尾的。

In [4]: s = "hello123"

In [5]: s[-1].isdigit()
Out[5]: True

这里有几个字符串的例子:

In [7]: for s in ['hello12324', 'hello', 'hello1345252525', 'goodbye']:
   ...:     print s, s[-1].isdigit()
   ...:     
hello12324 True
hello False
hello1345252525 True
goodbye False

我完全支持使用正则表达式的解决方案,不过这里有一种(虽然不太好看)的方法可以获取数字。再说一次,正则表达式在这里要好得多 :)

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'
69

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 是用来匹配一个数字,比如0到9之间的任何一个数字。\d+ 则表示匹配一个或多个数字,也就是说它会尽量匹配尽可能多的连续数字。最后,$ 是用来表示字符串的结尾,也就是你要匹配的内容必须在字符串的最后。

撰写回答