Equivalent of Perl chomp?

Steve Holden sholden at holdenweb.com
Fri Feb 1 18:21:18 EST 2002

"Thomas Bellman" <bellman at lysator.liu.se> wrote in message
news:a3f7dh$lq9$1 at news.island.liu.se...
> Stefan Schwarzer <s.schwarzer at ndh.net> writes:
> > It might be interesting to give some examples of code that "wants"
> > We then could see if there is a pythonic way to make a chomp-like
> > 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.
Perhaps I'm just lazy, but why not process

    for line in file(filename).read().split("\n"):

under such circumstances? True, this can be a pain if you need to read
Windows files under Unix or if you are using binary mode under Windows.
Otherwise, as long as the files aren't uncomfortably large, it avoids the
need to chomp.

Consulting, training, speaking: http://www.holdenweb.com/
Python Web Programming: http://pydish.holdenweb.com/pwp/

More information about the Python-list mailing list