Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring or removing line breaks python [duplicate]

I'm sorry for the noobish question, but none of the answers I've looked at seem to fix this. I'd like to take a multi-line string like this:

myString = """a
b
c
d
e"""

And get a result that looks like or that is at least interpreted as this:

myString = "abcde"

myString.rstrip(), myString.rstrip(\n), and myString.rstrip(\r) don't seem to change anything when I print this little "abcde" test string. Some of the other solutions I've read involve entering the string like this:

myString = ("a"
"b"
"c")

But this solution is impractical because I'm working with very large sets of data. I need to be able to copy a dataset and paste it into my program, and have python remove or ignore the line breaks.

Am I entering something in wrong? Is there an elegant solution to this? Thanks in advance for your patience.

like image 531
John Avatar asked Sep 13 '13 22:09

John


People also ask

Does Rstrip remove newline?

The rstrip() method removes any trailing character at the end of the string. By using this method, we can remove newlines in the provided string value.

How do I remove spaces between lines in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.

What is Linebreak in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.


1 Answers

Use the replace method:

myString = myString.replace("\n", "")

For example:

>>> s = """
test
test
test
"""
>>> s.replace("\n", "")
'testtesttest'
>>> s
'\ntest\ntest\ntest\n' # warning! replace does not alter the original
like image 119
tckmn Avatar answered Sep 27 '22 19:09

tckmn