简体   繁体   中英

Ignoring or removing line breaks python

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.

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
>>> myString = """a
... b
... c
... d
... e"""
>>> ''.join(myString.splitlines())
'abcde'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM