【问题标题】:Why do i get an empty list when i look for numbers with regular expressions为什么我用正则表达式查找数字时得到一个空列表
【发布时间】:2020-06-26 02:34:24
【问题描述】:

所以我一直在做一个在线 python 课程,其中一个作业让我查看一个文本文件,找到所有数字,并打印出总和,我能够检索所有数字但是我的代码也返回空列表,代码如下:

import re
handle = open('words.txt')

for line in handle:
    line = line.strip()
    numbers = re.findall('[1-9]+', line)
    print(numbers)

【问题讨论】:

  • 你的预期输出是什么?
  • 如果你想匹配10,你可能想使用[0-9]+。每次一行不包含任何数字时,您都会得到一个空列表。

标签: python filehandle python-re


【解决方案1】:

尝试使用\d+(数字):

numbers = re.findall(r'\d+', line)

至于您现有的正则表达式,可能是因为您缺少 0 ([0-9]+)。

【讨论】:

    猜你喜欢
    • 2021-11-23
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多