Home » Python » Remove Line Break in a String using Python

Remove Line Break in a String using Python

Python’s triple quotes (“””) allow strings to span over multiple lines. To remove line breaks in a string in Python, use the str.replace() to find occurrences of “\n” and replace them with “”.

str.replace() in Python replaces the specified phrase in the string with the new phrase. Use the replace() method to remove all instances of line breaks in 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 line breaks in a string with a space.

Use str.replace() to remove line breaks in a string in Python

To remove line breaks in a string in Python:

  1. Call the str.replace() on a string and pass a ‘\n’ to search for and a new character space ‘ ‘ for a replacement.
  2. The replace() returns a copy of the string in which all occurrences of line breaks are replaced by a new character (space) ”.
str = """Welcome
To
Python"""
print (str)

str1 = str.replace("\n",' ')
print(str1)

In the above Python program, we pass the following parameters to replace():

  1. str variable stores the string that contains a multiline string using Python’s triple quotes.
  2. Use str.replace() to remove line breaks in a string.
  3. character ‘\n’ to search for in the string.
  4. replacement character ‘ ‘ (space). 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 line breaks in a string with a space in Python is:

Welcome
 To
 Python

Welcome To Python

Cool Tip: How to remove a comma from a string in Python!

Conclusion

I hope the above article on how to remove line breaks in 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.

Leave a Comment