[英]Return true if only if the lines are all not start with spaces
lines = files.readlines()
for line in lines:
if not line.startswith(' '):
res = True
if line.startswith(' '):
res = False
return res
This is my code, however, it returns True for at least one line is not starting with space. 这是我的代码,但是对于至少一行不是以空格开头的行,它返回True。 How do I fix it so it will return True if only if every line in the file I opened starts with something other than space. 我如何解决它,以便仅当我打开的文件中的每一行都以空格以外的其他内容开头时,它才会返回True。 If at least one line starts with a space then return False. 如果至少一行以空格开头,则返回False。
Demo: 演示:
>>> lines = ['a', ' b', ' d']
>>> all(not x.startswith(' ') for x in lines)
False
>>> lines = ['a', 'b', 'd']
>>> all(not x.startswith(' ') for x in lines)
True
Also there's no need to load all lines in memory, simply iterate over the file object: 同样,也不需要加载内存中的所有行,只需遍历文件对象即可:
with open('filename') as f:
res = all(not line.startswith(' ') for line in f)
Use the all
built-in. 使用all
内置的。
return all(not line.startswith(' ') for line in lines)
The all()
function from the docs: 来自文档的all()
函数:
all(iterable) -> bool Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True.
You could also use the any
built-in in the same manner. 您也可以以相同的方式使用any
内置函数。
return not any(line.startswith(' ') for line in lines)
The any()
function from the docs: 来自文档的any()
函数:
any(iterable) -> bool Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False.
with open('filename') as f:
res = True
for line in f:
if line.startswith(' '):
res = False
break
return res
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.