尝试找出如何编写if循环来检查一行是否为空。
该文件有许多字符串,其中一个是空行,用于与其他语句分隔(不是""
;我认为是一个回车后跟另一个回车)
new statement
asdasdasd
asdasdasdasd
new statement
asdasdasdasd
asdasdasdasd
由于我使用的是文件输入模块,有没有办法检查一行是否为空?
使用这段代码,它似乎可以工作,谢谢大家!
for line in x:
if line == '\n':
print "found an end of line"
x.close()
发布于 2011-10-26 06:19:38
如果您想忽略仅包含空格的行:
if not line.strip():
... do something
空字符串是假的值。
或者,如果您真的只想要空行:
if line in ['\n', '\r\n']:
... do something
发布于 2014-03-26 22:59:38
我使用以下代码来测试带有或不带有空格的空行。
if len(line.strip()) == 0 :
# do something with empty line
发布于 2011-10-26 06:10:12
line.strip() == ''
或者,如果您不想“吃掉”由空格组成的行:
line in ('\n', '\r\n')
https://stackoverflow.com/questions/7896495
复制相似问题