Trying to figure out how to write an if cycle to check if a line is empty.
The file has many strings, and one of these is a blank line to separate from the other statements (not a ""
; is a carriage return followed by another carriage return I think)
new statement asdasdasd asdasdasdasd new statement asdasdasdasd asdasdasdasd
Since I am using the 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()
Use len to Check if a String in Empty in Python Let's see how we can use this function to check if a string is empty or not: # Using len() To Check if a String is Empty string = '' if len(string) == 0: print("Empty string!") else: print("Not empty string!") # Returns # Empty string!
Check if a string contains newlines using the 'in' operator With the 'in' operator, we can check for a specified value in a string. However, this method returns True if the value exists. Otherwise, returns False.
Python String isspace() Method The isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters such as: ' ' – Space. '\t' – Horizontal tab.
If you want to ignore lines with only whitespace:
if line.strip(): ... do something
The empty string is a False value.
Or if you really want only empty lines:
if line in ['\n', '\r\n']: ... do something
I use the following code to test the empty line with or without white spaces.
if len(line.strip()) == 0 : # do something with empty line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With