我如何计算一个字符串中的数字数量

问题描述 投票:0回答:2

我想计算s字符串中的数字数量。

在此字符串中:

“ 2019年对于10至20岁至60岁的幸运者来说是伟大的一年。”

结果应为4(2019,10,20,60)谢谢

python string tokenize
2个回答
0
投票

re.findall是处理此问题的非常简单的方法:

re.findall

这假定数字不是带小数点或其他非整数的浮点数。


0
投票

[我将使用import re s = "2019 was a great year for 10 fortunate people in ages 20 to 60." # find all groups of digits re.findall(r'\d+', s) # ['2019', '10', '20', '60'] 将字符串拆分为令牌,并在每个令牌上进行迭代,并使用像s.split(' ')这样的正则表达式来测试每个字符是否为数字,并在一个整数中累积良好的测试响应。

© www.soinside.com 2019 - 2024. All rights reserved.