Python rstrip – remove training spaces and newline

Python rstrip can be used to removed trailing whitespaces (spaces, newlines, tabs, etc.) from a string. It

Usage

newstring = s.rstrip([chars])

If chars string is not specified then all trailing whitespaces are removed. Otherwise only characters specified in string chars are removed.

Example – remove all trailing whitespaces

s = "Hello \t "
news = s.rstrip()
print "\"" + s + "\""
print "\"" + news + "\""
"Hello 	 "
"Hello"
Env: Python 2.7.6

Example – remove trailing newlines

s = "Hello   \n"
news = s.rstrip("\n")
print "\"" + s + "\""
print "\"" + news + "\""
Env: Python 2.7.6
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments