stripping spaces in front of line

Tim Chase python.list at tim.thechases.com
Fri Mar 3 23:18:05 EST 2006


> wish to ask a qns on strip
> i wish to strip all spaces in front of a line (in text file)
> 
> f = open("textfile","rU")
> while (1):
>         line = f.readline().strip()
>         if line == '':
>                 break
>         print line
> f.close()

Yes, that would be a way to do it.

> in "textfile", i added some spaces in and then ran the code, it prints
> out the lines without the spaces in front. I double checked "textfile"
> and it does contains some lines with spaces in front.
> Is it true that "readline().strip()" perform the removing of spaces in
> front of a line as well?

Am I missing something here?  You've just written a program 
that does exactly what you ask, and shown to yourself that 
*yes*, calling "strip()" does indeed strip off whitespace. 
You state "it prints out the lines without the spaces in 
front".  Yup...I'd guess that's pretty strong evidence that 
"readline().strip()" performs the removing of spaces in 
front of a line as well.

> Is it documented anywhere?

Run a python interpreter shell.

 >>> help("".strip)
 >>> help("".rstrip)
 >>> help("".lstrip)

This within-the-interpreter is one of my favorite language 
features in Python (and maddening when 3rd-party library 
developers don't document everything as well as the base 
modules are)

-tkc









More information about the Python-list mailing list