python - 从字符串中删除非数字字符

标签 python

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/

相关文章:

python - 根据 Entry 值链接 Tkinter 标签

python - 将连续的数字序列附加到列表中

python - 如何在 Python 中设置顶级变量?

python - Beautifulsoup 无法找到名称中带有连字符的类

python - 将 IP 地址从长整型格式转换为字符串

python - 将自定义错误栏添加到seaborn FacetGrid,确认色调和分类x顺序

python - 连接不同文件形状的多个文件抛出错误 :ValueError: Shape of passed values is (88, 57915),索引暗示 (88, 57906)

python - 更新到版本 2.1.2 后,Matplotlib hatch 不起作用

python - 检查句子中的单词

python - 根据第一列中的值对文件进行排序