python:如何检查一行是否为空行

试图弄清楚如何编写一个if循环来检查一行是否为空。

该文件有很多string,其中之一是一个空行来分隔其他语句(不是“”;是一个回车,后面跟着另一个回车,我认为)

new statement asdasdasd asdasdasdasd new statement asdasdasdasd asdasdasdasd 

由于我正在使用文件input模块,有没有办法来检查一行是否为空?

使用这个代码似乎工作,谢谢大家!

 for line in x: if line == '\n': print "found an end of line" x.close() 

如果你想忽略只有空格的行:

 if not line.strip(): ... do something 

空string是一个False值。

或者如果你真的只想要空行:

 if line in ['\n', '\r\n']: ... do something 

我使用下面的代码来testing带有或没有空格的空行。

 if len(line.strip()) == 0 : # do something with empty line 
 line.strip() == '' 

或者,如果你不想“吃掉”由空格组成的行,

 line in ('\n', '\r\n') 

您应该使用rU打开文本文件,以便正确转换换行符,请参阅http://docs.python.org/library/functions.html#open 。 这样就不需要检查\r\n

我认为使用正则expression式更健壮:

 import re for i, line in enumerate(content): print line if not (re.match('\r?\n', line)) else pass 

这将在Windows / Unix中匹配。 另外,如果您不确定只包含空格字符的行,可以使用'\s*\r?\n'作为expression式