Any algorithm to preserve whitespaces?
d at davea.name
Wed Jan 23 11:34:45 CET 2013
On 01/23/2013 04:20 AM, Santosh Kumar wrote:
> I am in a problem.
> words = line.split(' ')
> preserve whitespaces but the problem is it writes an additional line
> after every line.
Think about what you said. It might be clearer if you wrote:
"but the problem is it doesn't strip off the newline (which is whitespace)."
You might want to fix it by doing an rstrip(), as Peter said, or you
might want to check if the last character is \n, and delete it if so.
Or you might want to fix the other logic where you use the reconstituted
line, making sure it doesn't add an extra newline to a line that already
Best answer depends on whether there might be other whitespace at the
end of the line, and on whether you consider the newline part of the
last field on the line.
Chances are that Peter's response is the one you want, but I had to
point out that without a spec, we're really just guessing. For another
example, suppose that some of the words in the file are separated by
tabs. If so, perhaps you'd better rethink the whole split logic.
More information about the Python-list