Removing newlines from string on windows (without replacing)
John Yeung
gallium.arsenide at gmail.com
Sun Jul 26 13:54:52 EDT 2009
On Jul 26, 1:13 pm, Tom <Tom.su... at gmx.com> wrote:
> The thing that was messing it up was that the endlines are handled
> differently on each each OS, so I changed the code to strip the
> endlines to be:
>
> if os.name == "nt":
> s = sauce.rstrip("\r\n")
> else:
> s = sauce.replace("\n", "")
Well, this is doing two different things. When os.name is 'nt', you
are getting rid of all *trailing* CRLFs. Otherwise, you are getting
rid of all LFs *anywhere in the string*. (Even if it so happens sauce
will only ever have LFs at the end, it's still better to use the
method that is closest to your intended meaning.)
Personally, I prefer using sauce.rstrip() with no parameters (one of
the suggestions Rhodri mentioned) if it's not important to preserve
trailing spaces, since this will work regardless of end-of-line style
(and typically, trailing spaces, tabs, etc. are undesirable anyway).
John
More information about the Python-list
mailing list