PasLeChoix
PasLeChoix

Reputation: 311

why pycharm gives a wrong condition check?

I have a string to be read from a file, there are cases that the readline() will return a blank line and I need to check that, please see the screenshot below and it would be appreciated if anyone can explain to me why it gives a wrong result:

enter image description here

As you can see from the screenshot, line='\n', why the expression's evaluation result is False?

There for sure are alternative way to check the blank line, but I am just very curiously wanting to know why my this script is not working.

Thank you.

Thanks.

Upvotes: 0

Views: 97

Answers (2)

user2390182
user2390182

Reputation: 73470

Your input file most likely contains some nasty characters, like "zero width space" or "invisible separator". You can output these if you print (or evaluate) repr(line):

with open('data.txt', 'w') as f:
    f.write(u"\n")
    f.write(u"\u200B\n")  # zero width space
    f.write(u"\u2063\n")  # invisible separator
    f.write(u"\n")


with open('data.txt', 'r') as f:
    for line in f:
        print(repr(line))

If you debug the above, you will be able to replicate your behaviour for lines 2 and 3, but not for lines 1 and 4. Note that these characters are not visible in most fonts (they do not take up any space!), and simply printing/displaying them (as does the hovering in the debugger) will thus not reveal that they are even there.

In the "evaluate expression" dialog in PyCharm, simple evaluate "repr(line)" to see what's really in it.

Upvotes: 1

Yevhen Kuzmovych
Yevhen Kuzmovych

Reputation: 12140

'\n' is not a blank line. "" is. So you can check if line == "": or if not line:. And if you read from file python will remove \n from the line. So if it is empty (has only new line character) it will return an empty string.

Upvotes: 0

Related Questions