python - 如何从字符串中选择数字直到出现第一个非数字字符?

标签 python python-3.x

我有一组字符串,例如:

"0"
"90/100"
None
"1-5%/34B-1"
"-13/7"

我想将它们转换为整数(或 None),以便我从头开始选择数字并在第一个非数字字符处停止。这样上面的数据就变成了:

0
90
None
1
None

我尝试做类似下面的代码,但遇到了多个问题,比如 int(new_n) 行导致 ValueErrornew_n 只是空字符串。即使没有它,代码看起来也很糟糕:

def pick_right_numbers(old_n):
    new_n = ''
    numbers = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
    if old_n is None:
        return None
    else:
        for n in old_n:
            if n in numbers:
                new_n += n
            else:
                return int(new_n)
        if new_n:
            return int(new_n)
        else:
            return None

有人可以用这个把我推向正确的方向吗?

最佳答案

这就是您正在寻找的那种东西吗?

import re
data = ['0', '90/100', None, '1-5%/34B-1', '-13/7']

def pick_right_numbers(old_n):
    if old_n is None:
        return None
    else:
        digits = re.match("([0-9]*)",old_n).groups()[0]
        if digits.isdigit():
            return int(digits)
        else:
            return None

for string in data:
    result = pick_right_numbers(string)
    if result is not None:
        print("Matched section is : {0:d}".format(result))

它使用re(模式匹配)来检测字符串开头的数字 block (匹配只匹配字符串的开头,搜索会在字符串的任何位置找到一个 block )。 它检查匹配项,确认匹配项是数字(否则最后一个数据元素匹配,但为空字符串)并将其转换为整数以返回。

关于python - 如何从字符串中选择数字直到出现第一个非数字字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38390640/

相关文章:

python - 在 BeautifulSoup 中打印和格式化结果

python - 某些数据未存储在数组中

python - 如何使用python监控全局键盘事件?

python - SqlAlchemy Core 和裸存在查询

python - 如何实现使用类和当前对象(self)的python类函数?

python-3.x - 使用 --ignore 和 --junitxml 进行 pytest 测试生成带有忽略测试的 xml

python - 如何在 Pandas 数据框中以非常特定的方式处理特定值?

python-3.x - python apschedular RedisJobStore 不在 redis 缓存中存储作业

python - 使用 numpy 连接 2 个列表

python - 在python中创建字典的字典