Equivalent of Perl chomp?

hamish_lawson hamish_lawson at yahoo.co.uk
Wed Jan 30 10:05:09 EST 2002


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