Python 为什么我在使用re.findall()时总是得到一个空列表?
嗨,我正在努力解决这个问题。我不需要答案,只需要解释一下为什么最后一个总是空的。我是否错误地使用了re.findall() 文件的最后一行似乎不包含任何数字。由于在循环后打印出Python 为什么我在使用re.findall()时总是得到一个空列表?,python,regex,Python,Regex,嗨,我正在努力解决这个问题。我不需要答案,只需要解释一下为什么最后一个总是空的。我是否错误地使用了re.findall() 文件的最后一行似乎不包含任何数字。由于在循环后打印出lst,因此lst变量将由最后一行的re.findall值赋值。如果最后一行desn不包含任何数字,则findall方法将返回空列表。您可以在for循环的末尾打印出lst: import re fhand = open("regex_sum_196551.txt") lst=list() regex = '[0-9]+'
lst
,因此lst
变量将由最后一行的re.findall
值赋值。如果最后一行desn不包含任何数字,则findall
方法将返回空列表。您可以在for循环的末尾打印出lst
:
import re
fhand = open("regex_sum_196551.txt")
lst=list()
regex = '[0-9]+'
#iterate through each line
for line in fhand:
#strip default whitespace charachters from the ends of the line
line=line.rstrip()
#look for all integers that match the regex in the line and add to the list
lst = re.findall(regex,line)
print(lst)
或者将列表扩展为@wpercy answer。立即重新定义
lst
每一行,而不保存结果。也许你的意思是没有for循环的类似lst=re.findall(regex,fhand.read())
的东西?
#iterate through each line
for line in fhand:
#strip default whitespace charachters from the ends of the line
line=line.rstrip()
#look for all integers that match the regex in the line and add to the list
lst = re.findall(regex,line)
print(lst)