Python remove whitespace from start and end of string; In this python post, you will learn how to remove the start and end string whitespace spaces, characters in a string in python.
Whenever you work in any programming language. So many times you need to remove some whitespace spaces, tab space, characters from the string that you have. Such as removing whitespace from beginning and end (both sides) of a string in python.
Python Trim String
If you want to trim the whitespaces, characters and leading & trailing spaces from Python string then you can use the following python built-in methods:
- strip(): It returns a new string after removing (beginning and end) any leading and trailing whitespaces including tabs (\t).
- rstrip(): It returns the new string with trailing whitespace removed. It’s easier to remember as removing the white spaces from a “right” side of a string.
- lstrip(): It returns the new string with leading whitespace removed, or removing whitespaces from the “left” side of the string.
Python has many built-in functions/methods for manipulation with strings, which you can check here (python string methods).
1: Python strip Trim String
Python strip() in-built method, which is used to remove all the leading and trailing spaces from a string (beginning and end (both sides) of a string).
The syntax of strip() is:
string.strip([chars])
strip() Parameters
- chars (optional) – a string specifying the set of characters to be removed.
If the chars argument is not provided, all leading and trailing whitespaces are removed from the string.
Example 1:
str = ' xoxo love xoxo '
# Leading whitepsace are removed
print(str.strip())
print(str.strip(' xoxoe'))
Output
xoxo love xoxo lov
2: Python trim string from left
Python lstrip() method returns a copy of the string with leading characters removed (based on the string argument passed). If no argument is passed, it removes leading spaces.
The syntax of lstrip() is:
string.lstrip([chars])
lstrip() Parameters
- chars (optional) – a string specifying the set of characters to be removed.
If the chars argument is not provided, all leading whitespaces are removed from the string.
Example 1:
str = ' this is first left string '
# Leading whitepsace are removed
print(str.lstrip())
Output
this is first left string
3: Python trim string from Right
python rstrip() method returns a copy of the string with trailing characters removed (based on the string argument passed). If no argument is passed, it removes trailing spaces.
The syntax of rstrip() is:
string.rstrip([chars])
rstrip() Parameters
- chars (optional) – a string specifying the set of characters to be removed.
If the chars argument is not provided, all whitspaces on the right are removed from the string.
Example 1:
str = ' this is right side'
# Leading whitepsace are removed
print(str.rstrip())
Output
this is right side
Recommended Python Programs