Nir Nir - 1 year ago 50
Python Question

Remove \n from triple quoted string in python

I have the following string:

string = """
Hello World

I want to clear all the line-breaks from the string in python.

I tried


But it's not working as desired.

What I should do?

I'm using python 3.3


Answer Source

str.strip removes whitespace from the start and the end of the string.

>>> string
'\nHello World\n123\nHelloWorld\n'
>>> string.strip()
'Hello World\n123\nHelloWorld'

If you want to remove the new line characters inside of the string, you can replace them by something else using str.replace:

>>> string.replace('\n', ' ')
' Hello World 123 HelloWorld '