faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

13 of 15 people (87%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

Strip newline without losing implied space

Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 31, Guido van Rossum


"""
Packages: text
"""

"""
> Newbie time! I've done my homework, but can't find the answer.

Now there's one more thing to learn: when asking a question about code
that doesn't work, always show the exact code you're using!

> I'm reading the contents of a .txt file in Windows NT. I want to strip
> out the newline characters to give me a long text string to work on.
> When I attempt to do so, I  lose valid blank spaces. This is apparently
> related to the Windows "feature" in which it hides spaces which would
> otherwise display at the beginning of a new line.

I'm guessing that you're using string.strip() or string.split()?
These strip all whitespace.

My personal idiom to remove the newline from the end of a line goes
something like this:
"""

import sys
while 1:
   line = sys.stdin.readline() # read one line, including \n
   if not line:
      break
   if line[-1] == '\n':
      print repr(line)  # added by the PSST
      line = line[:-1]
   # ...now it's safe to use it...
   print repr(line) # added by the PSST

"""
If you read the whole file in one fell swoop, here's the way to do it:
"""

import sys, string
data = sys.stdin.read() # read whole file
data = string.replace(data, "\n", " ") # replace newlines by spaces