
Python string strip(), lstrip(), rstrip() - Remove leading and trailing spaces from a string
How can we remove whitespaces and newlines from the ends of a string? In Python, the strip()
removes leading and trailing spaces from a string.
a = ' Book '
b = a.strip()
print(b) # Book
The strip()
trims whitespaces, tabs, and newlines. There were some spaces before and after Book
and removed by this method. Many other languages including Java calls this type of function "trim()". The following example shows the strip()
removes newlines from the ends of the string.
s = """
abc
"""
t = s.strip()
print(t) # abc
Note that you can insert newlines into a string using triple quotes.
lstrip(), rstrip(), strip()
Python string has three trimming methods: lstrip()
, rstrip()
, strip
. The lstrip()
means "left strip" and removes spaces and newlines from the left side of a string. The rstrip()
means "right strip" and removes spaces and newlines from the right side of a string.
s = ' abc '
t1 = s.lstrip()
t2 = s.rstrip()
t3 = s.strip()
print(t1) # abc
print(t2) # abc
print(t3) # abc
The lstrip()
trims only leading spaces and the rstrip()
trims only trailing spaces.
Comments
Powered by Markdown