my_str = " This string contains spaces. "
#trim python string using strip() method
trimmmed_str = my_str.strip()
print(trimmmed_str)
#remove leading(beginning) whitespace
lstr = my_str.lstrip()
#remove trailing(end) whitespace
rstr = my_str.rstrip()
In the code snippet, we have a string variable my_str that contains a sentence. It has some space at its beginning and end. We are removing this space using the .strip() method of python string that will remove the space.
We can use the below python methods to remove trailing and leading whitespaces from a python string.
If you want to remove space or whitespace from both sides of the string, you can use the strip() method, Below is the example for that.
str = ' Hello World '
new_str = str.strip()
print(new_str)
# -> 'Hello World'
The Python string method lstrip() can be used to remove whitespace from the beginning of the string. Below is the code example
str = ' Hello World '
new_str = str.lstrip()
print(new_str)
# -> 'Hello World '
To remove trailing whitespace from a string, the python rstrip() method is used. It will remove all the spaces from the end of the string.\
Code Example:
str = ' Hello World '
new_str = str.lstrip()
print(new_str)
# -> ' Hello World'
0 Comments