Equivalent of Perl chomp?

Stefan Schwarzer s.schwarzer at ndh.net
Wed Jan 30 14:54:26 CET 2002

Hello Paul

Paul Watson wrote:
> What are some ways in Python to produce the equivalent of the Perl chomp
> function?  The chomp function in Perl removes the "newline" byte(s).
> I know about rstrip and strip.  I want to maintain any existing non-newline
> whitespace that exists at the end of the string.

If you don't mind readability ;-) how about

>>> chomp = lambda s: (s, s[:-1])[s[-1]=='\n']
>>> chomp('abc')
>>> chomp('abc\n')
>>> chomp('abc \n')
'abc '


More information about the Python-list mailing list