use*_*290 34 python regex string numbers
基本上我想知道我会怎么做.
这是一个示例字符串:
string = "hello123"
Run Code Online (Sandbox Code Playgroud)
我想知道如何检查字符串是否以数字结尾,然后打印字符串结尾的数字.
我知道对于这个特定的字符串,您可以使用正则表达式来确定它是否以数字结尾,然后使用字符串[:]来选择"123".但是,如果我循环使用这样的字符串文件:
hello123
hello12324
hello12435436346
Run Code Online (Sandbox Code Playgroud)
...然后由于数字长度的不同,我将无法使用字符串[:]来选择数字.我希望我能够清楚地解释我需要什么来帮助你们.谢谢!
Pet*_*ham 50
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()
Run Code Online (Sandbox Code Playgroud)
\d匹配数字,\d+表示匹配一个或多个数字(贪婪:尽可能多地匹配).并且$意味着匹配字符串的结尾.
Roc*_*key 20
这不会占字符串中间的任何内容,但它基本上表示如果最后一个数字是一个数字,则以数字结尾.
In [4]: s = "hello123"
In [5]: s[-1].isdigit()
Out[5]: True
Run Code Online (Sandbox Code Playgroud)
有几个字符串:
In [7]: for s in ['hello12324', 'hello', 'hello1345252525', 'goodbye']:
...: print s, s[-1].isdigit()
...:
hello12324 True
hello False
hello1345252525 True
goodbye False
Run Code Online (Sandbox Code Playgroud)
我完全和完全支持正则表达式解决方案,但这里有一个(不太漂亮)的方式,你可以得到这个数字.再一次,正则表达式在这里要好得多:)
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'
Run Code Online (Sandbox Code Playgroud)
另一种解决方案:查看您可以去除字符串末尾的 0-9 位数,并将该长度用作字符串的索引以拆分数字。(''如果字符串不以数字结尾则返回)。
In [1]: s = '12hello123558'
In [2]: s[len(s.rstrip('0123456789')):]
Out[2]: '123558'
Run Code Online (Sandbox Code Playgroud)