absolute removal of '\n' and the like

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Feb 10 19:31:08 EST 2006


On Fri, 10 Feb 2006 15:21:58 -0800, S Borg wrote:

> Hello,
> 
>  If I have a string, what is the strongest way to assure the
> removal of any line break characters?

What do you mean "strongest"? Fastest, most memory efficient, least lines
of code, most lines of code, least bugs, or just a vague "best"?


> Line break characters must always be the last character in a line, 

Must they? Are you sure? What happens if the file you are reading from
doesn't end with a blank line?


> so would this:    str = linestring[:-1]
>  work?

Using the name of a built-in function (like str) is called shadowing. It
is a BAD idea. Once you do that, your code can no longer call the built-in
function.

s = line[:-1] will work if you absolutely know for sure the line ends with
a newline.

This would be safer, if you aren't sure:

if line[-1] == '\n':
    s = line[:-1]
else:
    s = line

but that assumes that line is a non-empty string. If you aren't sure about
that either, this is safer still:

if line and line[-1] == '\n':
    s = line[:-1]
else:
    s = line

If you want to clear all whitespace from the end of the line, not just
newline, this is better still because you don't have to do any tests:

s = line.rstrip()

There is also a lstrip to strip leading whitespace, and strip() to strip
both leading and trailing whitespace.



-- 
Steven.




More information about the Python-list mailing list