Let’s say you want to extract all the lines of a file where the character at index 5 is not a space:
with open('sequences.gb') as f: for line in f: if line != ' ': print line[:-1]
Problem: short lines.
line might not be a valid index. Exception.
You might consider
line[5:6]. Normally this is the same as
line, but when
line is short then instead of raising an Exception it evaluates to the empty string,
In this case it will result in short lines being selected and printed. If the test was
if line[5:6] in string.letters then it will result in short lines being rejected. But that changes the semantics of the test for the lines that are long enough. If I had written
if ' '.startswith(line[5:6]) then I keep the same test semantics for long lines and I reject short lines. It’s weird and not clear though.
Sometimes this trick may be appropriate, and you may be able to tweak your test to accommodate it. Don’t let the clarity slide. There is a great deal of merit to:
if len(line) > 5 and line != ' '.