[英]python: how to check if a line is an empty line
试图弄清楚如何编写一个 if 循环来检查一行是否为空。
该文件有许多字符串,其中一个是与其他语句分开的空行(不是""
;我认为是回车后跟另一个回车)
new statement
asdasdasd
asdasdasdasd
new statement
asdasdasdasd
asdasdasdasd
由于我使用的是文件输入模块,有没有办法检查一行是否为空?
使用此代码似乎可以工作,谢谢大家!
for line in x:
if line == '\n':
print "found an end of line"
x.close()
如果你想忽略只有空格的行:
if not line.strip():
... do something
空字符串是一个 False 值。
或者,如果您真的只想要空行:
if line in ['\n', '\r\n']:
... do something
我使用以下代码来测试有无空格的空行。
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
。
我认为使用正则表达式更健壮:
import re
for i, line in enumerate(content):
print line if not (re.match('\r?\n', line)) else pass
这将在 Windows/unix 中匹配。 此外,如果您不确定仅包含空格字符的行,您可以使用'\\s*\\r?\\n'
作为表达式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.