Equivalent of Perl chomp?

Paul Watson pwatson at mail.com
Thu Jan 31 05:50:16 EST 2002


Thank you for all of the replies.  Given the replies, I am wondering if
Python treats "\n" as a platform independent newline.  I know it does when
using print.  However, the re.sub() example below makes me think that \n is
only a literal LF and does not resolve to CRLF on the DOS/Windows platform.
Is this just a function of it being used in re?  Yes, clearly, "\n"
generates CRLF when used in a print statement.

Does Python have something like Perl's $/ and $\ which are input and output
record separator values?  I am not trying to push Perl.  I'm trying to move
to Python and must have something for comparison.  Sorry.

Is chomp worth considering as an addition to the string functions?

"hamish_lawson" <hamish_lawson at yahoo.co.uk> wrote in message
news:mailman.1012403361.2370.python-list at python.org...
> Paul Watson wrote:
>
> > What are some ways in Python to produce the equivalent of the Perl
> > chomp function?
>
> Some of the other solutions offered don't remove *all* trailing CR or
> LF characters, as Perl's chomp function does. Here is a version that
> does:
>
> >>> def chomp(s):
> ... import re
> ... return re.sub(r"[\r\n]+$", "", s)
> ...
> >>> chomp("stuff   \r\n\r\n")
> 'stuff   '
> >>> chomp("stuff   \r\r\r")
> 'stuff   '
> >>> chomp("stuff   \n\n\n")
> 'stuff   '
> >>> chomp("stuff   ")
> 'stuff   '
> >>> chomp("stuff   \r\n   ")
> 'stuff   \r\n   '
>
> Note that Perl's version can also operate on a list of strings, but a
> more general approach is to use a list comprehension (Python 2.0+) or
> the map function:
>
> >>> lines = ["stuff   \r\r\r", "junk  \n\n", "nonsense  \r\n  "]
> >>> [chomp(s) for s in lines]
> ['stuff   ', 'junk  ', 'nonsense  \r\n  ']
> >>> map(chomp, lines)
> ['stuff   ', 'junk  ', 'nonsense  \r\n  ']
>
>
> Hamish Lawson
>
>
>





More information about the Python-list mailing list