How to trim whitespace from a string in python
In this article, you are going to learn about how to trim whitespace from a string in Python.
In general, a string is nothing but a sequence of multiple characters. In the Python programming language, strings are an array of bytes that represent Unicode characters and basically a data type that represents text-based data. Sometimes, we need to trim whitespace from a string. Here, whitespace means the extra space or any unnecessary space that do not need. To trim whitespace from a string is necessary and to do so python provides built-in methods like strip(), rstrip(), lstrip(). In this article, we will discover these methods and try to remove whitespace from a string in python.
strip() method
The strip() method is used to remove whitespace from a string and returns a new string after removing it. Let’s see the below code example:
my_str = " Hello "
# Befor trim whitespace
print(my_str)
# Using strip() method
trim_str = my_str.strip()
# After trim whitespace
print(trim_str)
# Output:
# " Hello "
# Hello
Here, you can see that, there’s extra whitespace before Hello and with the help of the strip() method we easily removed that whitespace.
rstrip() method
The strip() method is also used to remove whitespace from a string but it only removes the right side of whitespace from a string. This method is very useful if you want to remove the right side of the whitespace from a string. See the below code example:
my_str = " Hello "
# Befor trim whitespace
print(my_str)
# Using rstrip() method
trim_str = my_str.rstrip()
# After trim whitespace
print(trim_str)
# Output:
# " Hello "
# " Hello"
Here, in the output, you can see that the whitespace from the right side of the string has been removed because of using the rstrip() method.
lstrip() method
This method is almost the same as the rstrip() method but the only difference is that it removes the whitespace from the left side of a string. See the below code example:
my_str = " Hello "
# Befor trim whitespace
print(my_str)
# Using lstrip() method
trim_str = my_str.lstrip()
# After trim whitespace
print(trim_str)
# Output:
# " Hello "
# "Hello "
Here, you may notice that the whitespace from the left side of the string has been removed because of using the lstrip() method.
These are some useful methods of timing whitespace from a string and you may use these methods to perform this action in the python programming language.