-2

So I was writing this code where I needed to read lines of numbers from one file.

After some lines there is gap in one line and it continue. I did read that strip will delete some white spaces on the start and at the end of the line. But I dont really understand meaning in this code. Like if there is some text in line it will add another strip.

for line in file:      
            
            if line.strip(): 
                seznam_veci.append(line.strip())

I don't really understand how this work in this code.

  • 2
    "If the line stripped of preceding or trailing whitespace is not empty, then append that stripped value…" – deceze Apr 14 '23 at 13:32

1 Answers1

1

if line.strip(): means that it will enter the if only if the line is not just white spaces,

line.strip removes all of the white spaces left and right and you are left with an empty string which is falsey

Axeltherabbit
  • 680
  • 3
  • 20
  • \*which is *falsey*. It's not literally `False` at any point. – deceze Apr 14 '23 at 13:33
  • I believe that `__bool__` is implicitly called by the interpreter – Axeltherabbit Apr 14 '23 at 13:34
  • 1
    To clarify: `line.strip()` returns a new string without whitespace. If the resulting string is empty, its "truthiness" is false, so the stuff in the if statement isn't executed. Then line.strip is called again. A more up-to-date version would be to use walrus: `if stripped := line.strip(): ...` – Simon Lundberg Apr 14 '23 at 13:34
  • It's still misleading/wrong to say that an empty string *is `False`*. It *evaluates as `False` in a boolean context.* – deceze Apr 14 '23 at 13:35