【发布时间】:2019-02-17 15:19:46
【问题描述】:
我想要嵌套循环来测试是否所有元素都符合条件,然后返回 True。示例:
有一个给定的文本文件:file.txt,其中包含这种模式的行:
aaa:bb3:3
fff:cc3:4
字母、冒号、字母数字、冒号、整数、换行符。
一般来说,我想测试是否所有的行都匹配这个模式。但是,在这个函数中,我想检查第一列是否只包含字母。
def opener(file):
#Opens a file and creates a list of lines
fi=open(file).read().splitlines()
import string
res = True
for i in fi:
#Checks whether any characters in the first column is not a letter
if any(j not in string.ascii_letters for j in i.split(':')[0]):
res = False
else:
continue
return res
但是,即使第一列中的所有字符都是字母,该函数也会返回 False。我也想请你解释一下。
【问题讨论】:
标签: python python-3.x for-loop