- Python: Remove Newline Character from String
- What are Python Newline Characters
- Use Python to Remove All Newline Characters from a String
- Use Python to Remove Trailing Newline Characters from a String
- Use Python Regex to Remove Newline Characters from a String
- Conclusion
- Additional Resources
- Python Remove Newline From String
- Python Remove Newline From String
- Using strip() method to remove the newline character from a string
- Using replace() method to remove newlines from a string
- Using regex to remove newline character from string
- Remove Newline From String in Python
- Use the strip() Function to Remove a Newline Character From the String in Python
- Use the replace() Function to Remove a Newline Character From the String in Python
- Use the re.sub() Function to Remove a Newline Character From the String in Python
- Related Article — Python String
Python: Remove Newline Character from String
In this tutorial, you’ll learn how to use Python to remove newline characters from a string.
Working with strings in Python can be a difficult game, that often comes with a lot of pre-processing of data. Since the strings we find online often come with many issues, learning how to clean your strings can save you a lot of time. One common issue you’ll encounter is additional newline characters in strings that can cause issues in your work.
The Quick Answer: Use Python string.replace()
What are Python Newline Characters
Python comes with special characters to let the computer know to insert a new line. These characters are called newline characters. These characters look like this: \n .
When you have a string that includes this character, the text following the newline character will be printed on a new line.
Let’s see how this looks in practice:
a_string = 'Hello!\nWelcome to Datagy!\nHow are you?\n' print(a_string) # Returns # Hello! # Welcome to Datagy! # How are you?
Now that you know how newline characters work in Python, let’s learn how you can remove them!
Use Python to Remove All Newline Characters from a String
Python’s strings come built in with a number of useful methods. One of these is the .replace() method, which does exactly what it describes: it allows you to replace parts of a string.
# Use string.replace() to replace newline characters in a string a_string = 'Hello!\n Welcome to Datagy!\n How are you?\n' a_string = a_string.replace('\n','') print(a_string) # Returns: Hello! Welcome to Datagy! How are you?
Let’s see what we’ve done here:
- We passed the string.replace() method onto our string
- As parameters, the first positional argument indicates what string we want to replace. Here, we specified the newline \n character.
- The second argument indicates what to replace that character with. In this case, we replaced it with nothing, thereby removing the character.
In this section, you learned how to use string.replace() to remove newline characters from a Python string. In the next section, you’ll learn how to replace trailing newlines.
Tip! If you want to learn more about how to use the .replace() method, check out my in-depth guide here.
Use Python to Remove Trailing Newline Characters from a String
There may be times in your text pre-processing that you don’t want to remove all newline characters, but only want to remove trailing newline characters in Python. In these cases, the .replace() method isn’t ideal. Thankfully, Python comes with a different string method that allows us to to strip characters from the trailing end of a string: the .rstrip() method.
Let’s dive into how this method works in practise:
# Remove trailing newline characters from a string in Python a_string = 'Hello! \nWelcome to Datagy! \nHow are you?\n' a_string = a_string.rstrip() print(a_string) # Returns # Hello! # Welcome to Datagy! # How are you?
The Python .rstrip() method works by removing any whitespace characters from the string. Because of this, we didn’t need to specify a new line character.
If you only wanted to remove newline characters, you could simply specify this, letting Python know to keep any other whitespace characters in the string. This would look like the line below:
a_string = a_string.rstrip('\n')
In the next section, you’ll learn how to use regex to remove newline characters from a string in Python.
Tip! If you want to learn more about the .rstrip() (as well as the .lstrip() ) method in Python, check out my in-depth tutorial here.
Use Python Regex to Remove Newline Characters from a String
Python’s built-in regular expression library, re , is a very powerful tool to allow you to work with strings and manipulate them in creative ways. One of the things we can use regular expressions (regex) for, is to remove newline characters in a Python string.
Let’s see how we can do this:
# Use regular expressions to remove newline characters from a string in Python import re a_string = 'Hello! \nWelcome to Datagy! \nHow are you?\n' a_string = re.sub('\n', '', a_string) print(a_string) # Returns: Hello! Welcome to Datagy! How are you?
Let’s see what we’ve done here:
- We imported re to allow us to use the regex library
- We use the re.sub() function, to which we passed three parameters: (1) the string we want to replace, (2), the string we want to replace it with, and (3) the string on which the replacement is to be done
It may seem overkill to use re for this, and it often is, but if you’re importing re anyway, you may as well use this approach, as it lets you do much more complex removals!
Conclusion
In this post, you learned how to use Python to remove newline characters from a string. You learned how to do this using the string.replace() method, how to replace trailing newlines using .rstrip() , and how to accomplish this using regular expression’s sub() function.
Additional Resources
To learn more about related topics, check out the resources below:
Python Remove Newline From String
There are times where we need to remove the newline from string while processing massive data. This tutorial will learn different approaches to strip newline characters from string in Python.
Python Remove Newline From String
In Python new line character is represented with “ \n .” Python’s print statement by default adds the newline character at the end of the string.
There are 3 different methods to remove the newline characters from the string.
Using strip() method to remove the newline character from a string
The strip() method will remove both trailing and leading newlines from the string. It also removes any whitespaces on both sides of a string.
# strip() method to remove newline characters from a string text= "\n Welcome to Python Programming \n" print(text.strip())
Welcome to Python Programming
If the newline is at the end of the string, you could use the rstrip() method to remove a trailing newline characters from a string, as shown below.
# rstrip() method to remove trailing newline character from a string text= "Welcome to Python Programming \n" print(text.rstrip())
Welcome to Python Programming
Using replace() method to remove newlines from a string
The replace() function is a built-in method, and it will replace the specified character with another character in a given string.
In the below code, we are using replace() function to replace the newline characters in a given string. The replace() function will replace the old character and substitute it with an empty one.
Similarly, if we need to replace inside newline characters in a list of strings, we can iterate it through for loop and use a replace() function to remove the newline characters.
# Python code to remove newline character from string using replace() method text = "A regular \n expression is a sequence \n of characters\n that specifies a search\n pattern." print(text.replace('\n', '')) my_list = ["Python\n", "is\n", "Fun\n"] new_list = [] print("Original List: ", my_list) for i in my_list: new_list.append(i.replace("\n", "")) print("After removal of new line ", new_list)
A regular expression is a sequence of characters that specifies a search pattern. Original List: ['Python\n', 'is\n', 'Fun\n'] After removal of new line ['Python', 'is', 'Fun']
We can also use the map function in Python to iterate the list of strings and remove the newline characters, as shown below. It would be a more optimized and efficient way of coding when compared to the for a loop.
my_list = ["Python\n", "is\n", "Fun\n"] print(list(map(str.strip, my_list)))
Using regex to remove newline character from string
Another approach is to use the regular expression functions in Python to replace the newline characters with an empty string. The regex approach can be used to remove all the occurrences of the newlines in a given string.
The re.sub() function is similar to replace() method in Python. The re.sub() function will replace the specified newline character with an empty character.
# Python code to remove newline character from string using regex import re text = "A regular \n expression is a sequence \n of characters\n that specifies a search\n pattern." print(re.sub('\n', '', text)) my_list = ["Python\n", "is\n", "Fun\n"] new_list = [] print("Original List: ", my_list) for i in my_list: new_list.append(re.sub("\n", "", i)) print("After removal of new line ", new_list)
A regular expression is a sequence of characters that specifies a search pattern. Original List: ['Python\n', 'is\n', 'Fun\n'] After removal of new line ['Python', 'is', 'Fun']
Remove Newline From String in Python
- Use the strip() Function to Remove a Newline Character From the String in Python
- Use the replace() Function to Remove a Newline Character From the String in Python
- Use the re.sub() Function to Remove a Newline Character From the String in Python
Strings in Python can be defined as the cluster of Unicode characters enclosed in single or double quotes.
Like other popular programming languages, Python also has a newline character indicated by \n . It is essentially used to trace the culmination of a line and the emergence of a new line in a string.
Newline characters can also be used in f-strings. Moreover, according to the Python documentation, print statements add a newline character at the end of a string by default.
This tutorial will discuss different methods to remove a newline character from a string in Python.
Use the strip() Function to Remove a Newline Character From the String in Python
The strip() function is used to remove both trailing and leading newlines from the string that it is being operated on. It also removes the whitespaces on both sides of the string.
The following code uses the strip() function to remove a newline character from a string in Python.
str1 = "\n Starbucks has the best coffee \n" newstr = str1.strip() print(newstr)
Starbucks has the best coffee
The rstrip() function can be used instead of the strip function if there is only the need to remove trailing newline characters. The leading newline characters are not affected by this function and remain as they are.
The following code uses the rstrip() function to remove a newline character from a string in Python.
str1 = "\n Starbucks has the best coffee \n" newstr = str1.rstrip() print(newstr)
Starbucks has the best coffee
Use the replace() Function to Remove a Newline Character From the String in Python
Also known as the brute force method, It uses the for loop and replace() function. We look for the newline character \n as a string inside a string, and manually replace that from each string with the help of the for loop.
We use a List of strings and implement this method on it. Lists are one of the four built-in datatypes provided in Python and can be utilized to stock multiple items in a single variable.
The following code uses the replace() function to remove a newline character from a string in Python.
list1 = ["Starbucks\n", "has the \nbest", "coffee\n\n "] rez = [] for x in list1: rez.append(x.replace("\n", "")) print("New list : " + str(rez))
New list : ['Starbucks', 'has the best', 'coffee ']
Use the re.sub() Function to Remove a Newline Character From the String in Python
The re module needs to import to the python code to use the re.sub() function
The re module is a built-in module in Python, which deals with regular expression. It helps in performing the task of searching for a pattern in a given particular string.
The re.sub() function is essentially used to take a substring and replace its occurrence in the string with another substring.
The following code uses the re.sub() function to remove a newline character from a string in Python.
#import the regex library import re list1 = ["Starbucks\n", "has the \nbest", "coffee\n\n "] rez = [] for sub in list1: rez.append(sub.replace("\n", "")) print("New List : " + str(rez))
New List : ['Starbucks', 'has the best', 'coffee ']
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.