To trim a string in Python, you can use the strip()
, lstrip()
, and rstrip()
methods of the str class.
In this example,
" Hello World "
to the variable str1
.strip()
method on str1
to remove leading and trailing whitespace characters.str1 = " Hello World "
trimmedStr1 = str1.strip()
print('Trimmed string is: "{}"'.format(trimmedStr1))
Trimmed string is: "Hello World"
In this example,
" apple"
to the variable str2
.lstrip()
method on str2
to remove leading whitespace characters.str2 = " apple"
trimmedStr2 = str2.lstrip()
print('Trimmed string is: "{}"'.format(trimmedStr2))
Trimmed string is: "apple"
In this example,
"banana "
to the variable str3
.rstrip()
method on str3
to remove trailing whitespace characters.str3 = "banana "
trimmedStr3 = str3.rstrip()
print('Trimmed string is: "{}"'.format(trimmedStr3))
Trimmed string is: "banana"
In this tutorial, we learned How to Trim a String in Python language with well detailed examples.