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.
Solution
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.