strings = ["1 asdf 2", "25etrth", "2234342 awefiasd"] #and so on
获取 [1, 25, 2234342]
的最简单方法是什么?
如果没有正则表达式模块或像 (^[0-9]+)
这样的表达式,如何做到这一点?
最佳答案
可以编写一个辅助函数来提取前缀:
def numeric_prefix(s):
n = 0
for c in s:
if not c.isdigit():
return n
else:
n = n * 10 + int(c)
return n
示例用法:
>>> strings = ["1asdf", "25etrth", "2234342 awefiasd"]
>>> [numeric_prefix(s) for s in strings]
[1, 25, 2234342]
请注意,当输入字符串没有数字前缀(如空字符串的情况)时,这将产生正确的输出(零)。
根据 Mikel 的解决方案,可以编写一个更简洁的 numeric_prefix 定义:
import itertools
def numeric_prefix(s):
n = ''.join(itertools.takewhile(lambda c: c.isdigit(), s))
return int(n) if n else 0
关于python - 从字符串中删除非数字字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5074426/