Skip to main content
 首页 » 编程设计

python之仅当所有行都不以空格开头时才返回 true

2025年05月04日13wayfarer

lines = files.readlines() 
 
for line in lines: 
    if not line.startswith(' '): 
        res = True 
    if line.startswith(' '): 
        res = False 
return res 

这是我的代码,但是,如果至少有一行不是以空格开头,它会返回 True。我该如何修复它,以便仅当我打开的文件中的每一行都以空格以外的内容开头时,它才会返回 True。如果至少一行以空格开头,则返回 False。

请您参考如下方法:

使用all() :

演示:

>>> 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 

也不需要将所有行都加载到内存中,只需遍历文件对象即可:

with open('filename') as f: 
   res = all(not line.startswith(' ') for line in f)