Am1*_*3zA 11 python string split
我有一个字符串,"GoTo: 7018 6453 12654\n"我只想得到这样的数字['7018', '6453', '12654'],我尝试正则表达式,但我不能拆分字符串得到只是数字这里是我的代码:
样本1:
splitter = re.compile(r'\D');
match1 = splitter.split("GoTo: 7018 6453 12654\n")
my output is: ['', '', '', '', '', '', '', '', '7018', '6453', '12654', '']
Run Code Online (Sandbox Code Playgroud)
样本2:
splitter = re.compile(r'\W');
match1 = splitter.split("GoTo: 7018 6453 12654\n")
my output is: ['GoTo', '', '7018', '6453', '12654', '']
Run Code Online (Sandbox Code Playgroud)
Fré*_*idi 14
如果所有数字都是正整数,则可以使用isdigit()方法在没有正则表达式的情况下执行此操作:
>>> text = "GoTo: 7018 6453 12654\n"
>>> [token for token in text.split() if token.isdigit()]
['7018', '6453', '12654']
Run Code Online (Sandbox Code Playgroud)
>>> re.findall(r'\d+', 'GoTo: 7018 6453 12654\n')
['7018', '6453', '12654']
Run Code Online (Sandbox Code Playgroud)