35
loading...
This website collects cookies to deliver better user experience
\n
.” Python’s print statement by default adds the newline character at the end of the string.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
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
replace()
function is a built-in method, and it will replace the specified character with another character in a given string. 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.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']
my_list = ["Python\n", "is\n", "Fun\n"]
print(list(map(str.strip, my_list)))
['Python', 'is', 'Fun']
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']