Equivalent of Perl chomp?

Alex Martelli aleax at aleax.it
Thu Jan 31 11:14:50 EST 2002


"Paul Rubin" <phr-n2002a at nightsong.com> wrote in message
news:7xwuxyy0o9.fsf at ruckus.brouhaha.com...
> "Steve Holden" <sholden at holdenweb.com> writes:
> > def chomp(s):
> >     return s[:-1]
>
> That's incorrect.  It's more like chop than chomp.  Closer would be:
>
> def chomp(s):
>    if s[-1]=='\n': return s[:-1]
>    else: return s

Do we _want_ to raise an exception if s is empty?  I'd tend
to code this, intuitively, in a less strict/severe way:

def chomp(s):
  if s[-1:]=='\n': return s[:-1]
  else: return s

the slice s[-1:] is well-defined for any string s (it's the empty
string if s is empty), differently from the indexing s[-1] (raises
if s is empty), of course.

> However, chomp in perl actually changes the string, which can't be
> done in Python.

Of course -- the 'equivalent' has to be within Python semantics.


Alex






More information about the Python-list mailing list