[Tutor] Re: perl's chomp equivalent?
Wesley J. Chun
wesc@alpha.ece.ucsb.edu
Mon, 17 Jul 2000 17:40:45 -0700 (PDT)
> Date: Mon, 17 Jul 2000 17:21:35 -0400 (EDT)
> From: Tim Condit <timc@ans.net>
>
> > Is there anything similar to perl's chomp, which removes newline
> > characters from the end of a line? I'm using this, which works just fine
> > if not..
> >
> > for i in range(len(merge_file)):
> > if merge_file[i][-1] == "\n":
> > print merge_file[i][:-1]
> > else:
> > print merge_file[i]
tim,
there are a variety of solutions for your question. it all depends
on what your application is and how you want to approach it. as
some folks have already mentioned, there are the *strip() routines:
- - -
import string
string.lstrip() removes leading whitespace
string.rstrip() removes trailing whitespace
or a combo of the two...
string.strip() removes both leading and trailing whitespace
- - -
for i in range(len(merge_file)):
print string.strip(merge_file[i])
... or ...
for i in merge_file:
print string.strip(i)
also, as of Python 1.6/2.0, strings now have methods,
so you could do something like merge_file.rstrip(), etc.
finally, i noticed that the name of your variable has
the word "file" in it. i don't know about your situation
but many times, i have to read in files with extra whitespace
and in these situations, i always seem to have to do some
kind of postprocessing on them.
i found it quite useful to use *strip() along with map()
in these cases. rather than doing something like...
import string
f = open('foo.txt', 'r')
data = f.readlines()
f.close()
for eachLine in data:
eachLine = string.strip(eachLine)
... i can save some code using map():
import string
f = open('foo.txt', 'r')
data = map(string.strip, f.readlines())
f.close()
hope this helps!!
-wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall PTR, TBP Summer 2000
http://www.phptr.com/ptrbooks/ptr_0130260363.html
http://www.softpro.com/languages-python.html
wesley.j.chun :: wesc@alpha.ece.ucsb.edu
cyberweb.consulting :: silicon.valley, ca
http://www.roadkill.com/~wesc/cyberweb/