Python Practice › String Programs › Program 39
Remove newlines from a string
Write a Python program to remove newline characters from a string.
Input
"objectoriented\nprogramming\n"
Output
'objectoriented\nprogramming' 'objectorientedprogramming'
Approach
strip()for the ends,replace("\n", "")for everywhere.
Solution
text = "objectoriented\nprogramming\n"print(repr(text.rstrip("\n")))print(repr(text.replace("\n", "")))Output
'objectoriented\nprogramming' 'objectorientedprogramming'
Line by line
Line 2
rstrip("\n") removes only trailing newlines.
Line 3
replace removes them everywhere.
Learn the concept
New to this topic? Read the lesson, then come back.