Python Practice › String Programs › Program 39

Remove newlines from a string

EasyString Programs · 39 of 106

Write a Python program to remove newline characters from a string.

Advertisement
Input
"objectoriented\nprogramming\n"
Output
'objectoriented\nprogramming'
'objectorientedprogramming'

Approach

  1. strip() for the ends, replace("\n", "") for everywhere.

Solution

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

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs