perl chomp equivalent in python?
Justin Sheehy
dworkin at ccs.neu.edu
Thu Feb 10 16:31:26 EST 2000
Jeff Bauer <jbauer at rubic.com> writes:
> Justin Sheehy wrote:
> <snip>
> > The need for this is also somewhat doubtful. I have yet
> > to see a real (not contrived) example where string.rstrip()
> > wasn't the right choice for this sort of thing.
>
> In most cases trailing whitespace is probably insignificant,
> but it would be best not to assume this for all circumstances
> (e.g. tab-delimited files).
If you really feel the need to be more careful, you could do
something like:
(untested)*
import os
lines = open(file).readlines()
for line in lines:
if line[-len(os.linesep):] == os.linesep:
line = line[:-len(os.linesep)]
print line
However, in comparison to the original solution of stripping
a number of characters off without even checking what they are,
string.rstrip() is definitely preferable.
As I said before, in every real case I've seen for this sort of thing,
string.rstrip() was the Right Thing to do.
> I would not want to see string.rstrip() used in library
> modules, since it could result in a loss of data where the
> user might not be expecting whitespace to disappear.
That's silly. It should be used in any library module where its
behavior (stripping all whitespace from the end of a string) is
desired. In any case where that is not desired, of course it
shouldn't be used. It's just a matter of knowing what your intentions
and specifications are.
> Of all newgroups, certainly comp.lang.python would be
> sympathetic to this issue. ;-)
Last time I checked, Python wasn't sensitive to extra whitespace at
the _end_ of a line.
-Justin
* - Also, I have no idea about the behavior of such things on
non-UNIX-like operating systems. YMMV.
More information about the Python-list
mailing list