Equivalent of Perl chomp?

A Meowbot meowbot at meowing.net
Wed Jan 30 06:46:13 EST 2002


"Paul Watson" <pwatson at mail.com> 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.

You can trim CRLF or LF from one line with
re.sub('\\r?\\n$', '', some_string).

It might be a bit quicker to use some form of read() with
re.split('\\r?\\n', some_string).  Presence of '' at the end of the
list tells you if there was a trailing newline (which is nice to know
if you're not reading in line-sized chunks).




More information about the Python-list mailing list