Equivalent of Perl chomp?

Paul Rubin phr-n2002a at nightsong.com
Thu Jan 31 17:59:08 CET 2002


"Alex Martelli" <aleax at aleax.it> writes:
> 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.

Nice touch.  The several attempts it took to get this right convinces
me even more that chomp should be a built-in method on strings.



More information about the Python-list mailing list