pythonbuilt-in-types

Which built-in function should come first in this particular case?


In this particular part of the program, I couldn't really get why the .startswith function wasn't the first one to be used:

for line in fhand:
    line = line.rstrip()
    if not line.startswith('From ') : continue
    words = line.split()
    print words[2]

I mean, wouldn't it be faster than stripping every single line at the beginning? Why or why not?


Solution

  • It's not the first, because your line might end with whitespace. Consider the following strings:

    "From somebody"
    "From "
    

    The version you posted above removes the trailing whitespace, leaving "From somebody" and "From" respectively. For the second string, startswith now returns False instead of True as your version with swapped functions would.

    I guess this is some form of verification that there is actual content after the "From " part, which - compared to whitespace - does not get stripped away.