TL;DR
You can remove NewLine from String in python by using string’s
replace()
method.
Syntax:Related Articles
final_string=initial_string.replace('\n', '')
We need to preprocess information while working with data to get meaningful insights, one of them is removing stray Newline Characters from a string in Python.
Remove NewLine from String in Python
This Python tutorial demonstrates the use of replace()
, strip()
, re.sub()
, and splitlines()
to eliminate newline characters from the specified string.
Use str.replace()
to Remove Newline Characters From a Python String
The str.replace()
function takes oldvalue
and newvalue
as function parameters where oldvalue
will be replaced by newvalue
. For our code, the oldvalue
is \n
and newvlaue
would be a single whitespace.
Note that, the replace()
function can also take a count
parameter which denotes how many occurrences of oldvalue
we want to replace with newvalue
.
message = "\n Hi! \n How are you? \n" print("Before:" + message) new_message = message.replace('\n', '') print("After:" + new_message)
Before: Hi! How are you?
After: Hi! How are you?
Use str.strip()
to Remove Newline Characters From a Python String
The strip()
function truncates the trailing newline characters (\n
) and white spaces, which means it eliminates newline characters & whitespaces from both ends of the specified string (start and end).
message_one = "\n Hi! How are you? \n" print("Before:" + message_one) new_message_one = message_one.strip() print("After:" + new_message_one)
Before: Hi! How are you? After:Hi! How are you?
Remember that the strip()
function does not remove whitespaces and newline characters occurring in between the given string. See the following code fence.
message_two = "\n\n Hi! \n How are you? \n" print("Before:" + message_two) new_message_two = message_two.strip() print("After:" + new_message_two)
Before: Hi! How are you? After:Hi! How are you?
Removing trailing newline characters and whitespaces is the default behaviour of strip()
; otherwise, it can also remove the specified trailing characters, for instance, str.strip('2')
.
The resulting string returned by strip()
depends on what parameters are provided:
-
If no parameter is given then it removes trailing whitespaces, and newline characters and return a string without whitespaces, and newline at the start and end of the string. If the specified string does not has any trailing whitespace and newline then, it returns an original string as it is.
-
If we specify a character parameter for
strip()
, it removes them from the start/end of the string and returns the string without those characters. If the specified character parameter is not available at the start/end of the string then we’ll get the original string as it is.
Use str.splitlines()
to Remove Newline Characters From a Python String
As we have learned that str.strip()
will not remove newline characters that occur somewhere in the string, this is where str.splitlines()
comes into the picture and helps us to remove newline characters that occur at the start, end and on random places in a string.
This function splits the specified string into a list. This split happens as soon as the str.splitlines()
find a line break. Further, we use the join()
method to join all the chunks separated by whitespace.
def func(string): return ''.join(string.splitlines()) message = "\n Hi! \n How are you? \n" print("Before:", message) print("After:", func(message))
Before: Hi! How are you? After: Hi! How are you?
Here, we are getting the advantage of splitlines()
‘s default behaviour but we can also pass True
or False
as a parameter to splitlines()
based on whether we want to include line breaks or not.
If yes then, we will specify True
as a parameter; otherwise False
, which is its default behaviour.
Further reading:
Python Print without Newline
Print without Parentheses in Python
Use re.sub()
to Remove Newline Characters From a Python String
We can also truncate newline characters using the regex function, called sub()
. To use this function, we will import the re
module. In the following code, the re.sub()
function takes three parameters:
pattern
– It is a pattern or string that needs to be replaced.repl
– It is a pattern or string with which we will replace thepattern
.string
– It is a string on which there.sub()
will be executed.
Note that, re.sub()
can also take count
and flags
as parameters which are used to denote the number of replacements and aids to shorten the code respectively.
import re message = "\n Hi! \n How are you? \n" print("Before:" + message) new_message = re.sub('\n', '', message) print("After:" + new_message)
Before: Hi! How are you? After: Hi! How are you?
Now, what if we have to remove a new line from a list of strings in Python? Let’s see how we can do it in the following section.
Remove Newline from a List of Strings in Python
All the methods that we have learned in this tutorial, can be used to remove newline characters as follows but each will work with its pros and cons. See the following example.
my_list = ["I\n", "want to take the \nbest", "coffee\n\n "] replace_result = [] sub_result = [] strip_result = [] splitlines_result = [] for sub in my_list: replace_result.append(sub.replace("\n", "")) sub_result.append(re.sub("\n", "", sub)) strip_result.append(sub.strip()) splitlines_result.append(sub.splitlines()) print("New List : " + str(replace_result)) print("New List : " + str(sub_result)) print("New List : " + str(strip_result)) print("New List : " + str(splitlines_result))
New List : ['I', 'want to take the best', 'coffee '] New List : ['I', 'want to take the best', 'coffee '] New List : ['I', 'want to take the \nbest', 'coffee'] New List : [['I'], ['want to take the ', 'best'], ['coffee', '', ' ']]
Now, it’s up to you, you can choose any of these approaches based on your project requirements.