To remove new lines from a string in Python, use the str.replace() to find occurrences of “\n” and replace them with “”. A new line character in Python is “\n”
str.replace()
in Python replaces the specified phrase in the string with the new phrase. Use the replace() method to remove all instances of a new line from a string in Python. For example, replacing all instances of character ‘\n’ with ”
In this example, we will discuss how to use the str.replace() in Python to replace newline from a string.
Use str.replace() to remove new lines from a string in Python
To remove new lines from a string in Python:
- Call the
str.replace()
on a string and pass a ‘\n’ to search for a replacement and a new character ” for a replacement. - The
replace()
returns a copy of the string in which all occurrences of new lines are replaced by a new character ”.
str = "Welcome\n To\n Python" print (str) str1 = str.replace("\n",'') print(str1)
In the above Python program, we pass the following parameters to replace():
- str variable stores the string that contains multiline string break using newline character ‘\n’
- Use the
str.replace()
to remove new lines from a string. - character ‘\n’ to search for in the string
- replacement character ”. It will replace all occurrences of new lines ‘\n’ with ”
It will return the copy of the string and store it in the str1 variable and print using print() Python.
The output of the above program after removing new lines from a string in Python is:
Welcome
To
Python
Welcome To Python
Cool Tip: How to remove a comma from the list of strings in Python!
Conclusion
I hope the above article on how to remove new lines from a string in Python using str.replace() is helpful to you.
You can find more topics about the Python tutorials on the DataVisualizr Home page.