Wouldn't line.split('#')[0] also work and be shorter? Note: I haven't tested this!