In this tutorial, we will look at how to remove linebreaks from a string in Python with the help of some examples.
How to remove linebreaks from a string in Python?

You can use a combination of the string splitlines()
and join()
functions to remove linebreaks (or newline characters) from a string in Python. The following are the steps –
- Use the string
splitlines()
function to split the string into a list of strings by splitting the string at newline characters. - Apply the string
join()
function on the resulting list of strings to join them back with the line breaks removed.
For example, let’s say we have the following string –
# create a string with linebreaks s = "You are...\nMy fire\nThe one...\nDesire" # display the string print(s)
Output:
You are... My fire The one... Desire
Now, let’s use the string splitlines()
and join()
functions to remove the linebreaks from the string in the above example.
# remove linebreaks new_s = ' '.join(s.splitlines()) # display the string print(new_s)
Output:
You are... My fire The one... Desire
You can see that the resulting string does not contain any linebreaks. Note that here we use a single space character ' '
to join the lines together. You can use any character (or even an empty string) to join the strings together from a list using the string join()
function.
For more on the string splitlines()
function, refer to its documentation.
Using string replace()
to remove linebreaks
You can also use the string replace()
function to remove linebreaks from a string. The idea is to replace every occurrence of the newline character '\n'
in the string (usually with a single space or an empty string).
Let’s see it in action. We will use the same string as above.
# remove linebreaks new_s = s.replace('\n', ' ') # display the string print(new_s)
Output:
You are... My fire The one... Desire
We get the same results as above.
Note that if your string contains the carriage return character '\r'
along with the newline character (for example, on a Windows machine, linebreaks in a text may be represented by '\r\n'
) you can use the replace()
function twice.
Let’s look at an example.
# create a string with linebreaks s = "You are...\r\nMy fire\r\nThe one...\r\nDesire" # display the string print(s)
Output:
You are... My fire The one... Desire
We will use the string replace()
twice, first to replace '\r'
with an empty string and then to replace '\n'
with a single space, ' '
.
# remove linbreaks new_s = s.replace('\r','').replace('\n',' ') # displace the string print(new_s)
Output:
You are... My fire The one... Desire
The resulting string does not contain any linebreaks.
You might also be interested in –
- Python – Remove Non Alphanumeric Characters from String
- Remove First Character From String in Python
- Remove Last Character From String in Python
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.