Equivalent of Perl chomp?

Thomas Bellman bellman at lysator.liu.se
Fri Feb 1 18:12:49 EST 2002


Stefan Schwarzer <s.schwarzer at ndh.net> writes:

> It might be interesting to give some examples of code that "wants" chomp.
> We then could see if there is a pythonic way to make a chomp-like function
> unnecessary. Maybe there are better ways.

I have typically needed to strip newlines when I'm processing a
text file where each line is a record with fields separated by
some character.  If you just .split() on the separator, you end
up with an unwanted newline in the last field.

/etc/passwd is a good example of such a file under Unix.  Sure,
there's the pwd module, but 1) it only handles *that* format, not
other, formats, and 2) it really is an interface to the current
machines passwd database; if you want to process some random file
in /etc/passwd format, you can't use it.


Another occasion I have wanted a chomp(), is when I want to check
if the line ends in some special character (like \).  I can't
then just do

    for line in fp.xreadlines():
	if line[-1:] == "\\":
	    blahonga(line)

but instead have to do

    for line in fp.xreadlines():
	if line[-2:] == "\\\n":
	    blahonga(line)

and I find that less readable.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"Adde parvum parvo magnus acervus erit"       ! bellman @ lysator.liu.se
          (From The Mythical Man-Month)       ! Make Love -- Nicht Wahr!



More information about the Python-list mailing list