absolute removal of '\n' and the like

S

S Borg

Hello,

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

Line break characters must always be the last character in a line, so
would
this: str = linestring[:-1]

work?

This is my first real 'learning python' project, and I don't want to
get in the habit
of doing things the 'Java way'. Your comments and suggestions are very
much
appreciated.

thanks,

S
 
R

Russell Blau

S Borg said:
If I have a string, what is the strongest way to assure the
removal of any line break characters?

Line break characters must always be the last character in a line, so
would
this: str = linestring[:-1]

work?

Er, yes, if you don't mind (a) mangling any string that *doesn't* have a
newline as the last character, and (b) messing up any subsequent part of
your program that tries to use the built-in str() function (because you just
reassigned that name to something else).

I'd suggest:

foo = linestring.rstrip("\n")

You can also add to the quoted string any other characters you want to have
stripped; for example,

foo = linestring.rstrip("\n\r\t")

Or if you want to strip off *all* whitespace characters, just leave it out:

foo = linestring.rstrip()

Russ
 
S

Steven D'Aprano

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,284
Messages
2,571,413
Members
48,106
Latest member
JamisonDev

Latest Threads

Top