How do you enter line breaks with raw_input
? But, once you have a string with some characters in it you want to get rid of, just replace
them.
>>> mystr = raw_input['please enter string: ']
please enter string: hello world, how do i enter line breaks?
>>> # pressing enter didn't work...
...
>>> mystr
'hello world, how do i enter line breaks?'
>>> mystr.replace[' ', '']
'helloworld,howdoienterlinebreaks?'
>>>
In the example above, I replaced all spaces. The string '\n'
represents newlines. And \r
represents carriage returns [if you're on windows, you might be getting these and a second replace
will handle them for you!].
basically:
# you probably want to use a space ' ' to replace `\n`
mystring = mystring.replace['\n', ' '].replace['\r', '']
Note also, that it is a bad idea to call your variable
string
, as this shadows the module string
. Another name I'd avoid but would love to use sometimes: file
. For the same reason.
Problem
You have a very long string or one that include newline escape characters [\n]. You would like to use Python 3 in order to automatically delete those appended newlines added to your string.
In this post, we will outline three methods that you can use to delete newlines from a string. In this post we’ll discuss each technique and post example code that you can use to follow along.
Using rstrip[] method:
The rstrip[] method removes any trailing character at the end of the string. By using this method, we can remove newlines in the provided string value.
Code:
def removelines[value]:
return value.rstrip[]
mystring = 'This is my string. \n'
print["Actual string:",mystring]
print["After deleting the new line:",removelines[mystring]]
Output:
Actual string: This is my string
After deleting the new line: This is my string.
Using replace[] method:
To remove any of the newlines found between a string, we can use the replace method and get the newline removed.
Code:
def removelines[value]:
return value.replace['\n','']
mystring = 'This is my string \nThis comes in the next line.'
print["Actual string:",mystring]
print["After deleting the new line:",removelines[mystring]]
Output:
Actual string: This is my string
This comes in the next line.
After deleting the new line: This is my string This comes in the next line.
Using splitlines[] method:
The splitlines[] method helps to convert the lines into a split list. Hence, we can split our string into a list and then join it to form a string value.
Code:
def removelines[value]:
return ''.join[value.splitlines[]]
mystring = 'This is my string \nThis comes in the next line.'
print["Actual string:",mystring]
print["After deleting the new line:",removelines[mystring]]
Output:
Actual string: This is my string
This comes in the next line.
After deleting the new line: This is my string This comes in the next line.
Removing newlines from a Python list
In a similar fashion you can easily strip newlines off a list of strings.
Let’s assume you have the following list:
orig_lst = ['Python', 'R', 'GO\n', 'Haskell']
We can easily strip the newlines off the list elements with a list comprehension and the rstrip[] function:
new_lst = [x.rstrip[] for x in orig_lst]
print[new_lst]
Here’s is the result:
['Python', 'R', 'GO', 'Haskell']
Alternatively we can obtain the same result by using the replace[] function:
new_lst = [x.replace['\n',''] for x in orig_lst]
We can also replace the newline characters with a space:
new_lst = [x.replace['\n',' '] for x in orig_lst]
Table of Contents Hide
- 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
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.
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.
- strip[] method
- replace[] method
- re.sub[] method
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[]]
Output
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[]]
Output
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]
Output
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]]]
Output
['Python', 'is', 'Fun']
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]
Output
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']
- replace newline character,
- strip newline character
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.