cut off \n

Steven Taschuk staschuk at telusplanet.net
Mon Jun 9 13:06:10 EDT 2003


Quoth Andrew Wilkinson:
  [...]
> def remove_last_newline(line):
>     if line[-1] == "\n":
>         return line[:-1]
>     else:
>         return line

Note that this will raise an exception if line == ''.  Skip's
slightly different
    if line[-1:] == '\n':
will work in that case, as would using .endswith (which I
personally consider clearer in such cases).

  [...]
> Unfortunatly without a single line if-expression in Python I can't think of
> a single line solution to this problem.

Since you ask:
    line = line[:line.endswith('\n') and -1 or len(line)]   # Ick.
or
    line = line[:len(line)-line.endswith('\n')]             # *shudder*

But really, if it's so frequent an annoyance that you want a
one-liner, just write a function.

-- 
Steven Taschuk                                7\ 7'Z {&~         .
staschuk at telusplanet.net                        Y r          --/hG-
                                            (__/ )_             1^1`





More information about the Python-list mailing list