Python has three inbuilt function to trim string- strip(), lstrip(), rstrip(). These functions in python are used to trim whitespaces, tabs (\t), and newline (\n) from the string.
Before we learn to trim strings in python, let’s understand what each of these methods does.
Python strip(), lstrip(), rstrip()
- strip() – This function returns a new modified string after trimming leading and trailing whitespace (whitespaces on left and right), tabs (
\t
), and newline (\n
). - lstrip() – This function returns a new modified string after removing the whitespaces, tabs (
\t
), and newline (\n
) from the left (leading) side of the string. - rstrip() – This function returns a new modified string after removing the whitespaces, tabs (
\t
) and newline (\n
) from the right (trailing) side of the string.
Let’s see some examples of each method.
Example 1: strip()
mystr = "\n \t Remove Whitespaces \n"
print("Original string-",mystr)
print("Trimmed string-",mystr.strip())
Output:
Example 2: lstrip()
mystr = "\n \t Remove Whitespaces \n"
print("Original string-",mystr)
print("Trimmed string-",mystr.lstrip())
Output:
Example 3: rstrip()
mystr = '\n \t Remove Whitespaces \n'
print('Original string-',mystr)
print("Trimmed string-",mystr.rstrip())
Output:
The rstrip()
method only trims the right newline character (\n) of \n \t Remove Whitespaces \n
, the left-hand side of the string remains unaffected.