Python: how to check if a string is an empty line

trying to figure out how to write an if loop to check for a string.

There are many lines in the file, and one of them is an empty line to separate from other operators (and not ""; this is a carriage return followed by another carriage return, I think)

new statement asdasdasd asdasdasdasd new statement asdasdasdasd asdasdasdasd 

Since I am using a file input module, is there a way to check if a line is empty?

Using this code, it seems to work, thanks everyone!

 for line in x: if line == '\n': print "found an end of line" x.close() 
+54
python
Oct 25 2018-11-22T00:
source share
5 answers

If you want to ignore lines with spaces only:

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

An empty string is False.

Or if you really want only empty lines:

 if line in ['\n', '\r\n']: ... do something 
+73
25 Oct 2018-11-21T00:
source share

I use the following code to check for an empty string with or without spaces.

 if len(line.strip()) == 0 : # do something with empty line 
+12
Mar 26 '14 at 2:59
source share
 line.strip() == '' 

Or, if you do not want to β€œeat up” lines consisting of spaces:

 line in ('\n', '\r\n') 
+9
Oct. 25 '11 at 10:10
source share

You must open the text files using rU so that newlines are correctly converted, see http://docs.python.org/library/functions.html#open . Thus, there is no need to check \r\n .

+1
Oct 25 '11 at 10:22
source share

I find it more reliable to use regular expressions:

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

This will fit on Windows / unix. Also, if you are not sure about strings containing only char space, you can use '\s*\r?\n' as an expression

+1
Nov 11 '15 at 22:55
source share



All Articles