Equivalent of Perl chomp?

Paul Watson pwatson at mail.com
Thu Jan 31 20:32:24 EST 2002


Perl chomp only removes -all- traliing newlines when in paragraph mode.
Paragraph mode is when $/ is set to "".  The default mode is not paragraph
mode, so chomp removes only one (1) newline.

=== code
$s = "now\n\n\n";
print "length($s) = ".length($s)."\n";
chomp($s);
print "length($s) = ".length($s)."\n";

=== output
length(now


) = 6
length(now

) = 5


"Jeff Hinrichs" <jlh at cox.net> wrote in message
news:Hxk68.4423$Xk4.215834 at news1.east.cox.net...
> Actually, it doesn't appear to the real "chomp" from perl.
> > def chomp(s):
> >   if s[-1:]=='\n': return s[:-1]
> >   else: return s
> According to the def of chomp: "...removes all trailing newlines from the
> string"
> http://www.perldoc.com/perl5.6/pod/func/chomp.html
>
> So then wouldn't a more accurate representation of chomp be:
> def chomp(s):
>     while s[-1:]=='\n':
>         s = s[:-1]
>     return s
>
> -Jeff
> p.s. I'm a python newbie so if I made a bad string handling decision
please
> let me know.





More information about the Python-list mailing list