The function of trimming strings is to remove the unwanted characters from string data. Python string trim has various purposes in Python Programming Language. Some use of trimming is removing unnecessary spaces from user data, eliminating newline character from the end of the string data etc. When the user submits data by using form fields then unwanted spaces can be submitted with the data by mistake. This type of mistake will generate an error when the data is used for validation. So string trimming is essential for many cases.
Three functions are used in Python Trim for string trimming. These are strip(), lstrip() and rstrip(). The use of these functions is shown in this tutorial using examples. All trimming functions are used to remove any whitespaces from the starting and end of the python string. The following characters are considered whitespace in Python. The particular character range can be used without these whitespace characters.
Types of Trimming / Stripping in Python?
Trimming can be achieved by three ways in Python:
- Strip – When we use the strip() a new string is returned after removing any trailing spaces or leading spaces.
- R-strip – The rstrip() outputs a new string with only the trailing spaces removed. Hence the name rstring() i.e removing the spaces only from the right side of the string.
- L-Strip – lstrip() does the opposite of the R-strip. It removes the whitespaces from the beginning of the string, which is the left side.
Python Trim Using strip() Trim Method
The strip method will remove any trailing or leading of a given string including tab (\t) and return a new string.
To test the strip() method. Try the following example:
To strip or trim any white space character(s) present at the start or end of a given string, use the method strip() on the string.
Syntax of strip()
The syntax of the strip() function is:
string.strip(characters) |
Parameters of the strip() function in Python
Parameter characters
is optional. If nothing is passed as an argument to the strip() method, the set of white space characters is considered as characters
.
Return Value from the strip()
The strip() returns a copy of the string with both leading and trailing characters stripped.
- When the combination of characters in the chars argument mismatches the character of the string in the left, it stops removing the leading characters.
- Similarly, when the combination of characters in the chars argument mismatches the character of the string in the right, it stops removing the trailing characters.
Example to Trim a Python String Using strip() Function
Example 1: Python Program to Strip or Trim White Spaces at Start and End
In this Python example, we demonstrate the usage of the strip() method. We take a string that has some single white spaces at the start and end of the string.
#String you want to trim
str = ' Welcome to Python Pool '
#strip any white space characters
strippedString = str.strip()
print("Original String~~\n")
print(str)
print("\nString after stripping~~\n")
print(strippedString)
Output:
Original String~~ Welcome to Python Pool String after stripping~~ Welcome to Python Pool
In the above example, we have a total of five spaces. Three between Welcome to Python Pool and two at the beginning and end. When we apply strip() method these three space between the string remains untouched. Only the spaces at the beginning and end are trimmed.
Example 2: Python Program to Strip or Trim White Strip White Space Character(s)
In this Python example, we will take a string that has newline and tab space characters at the start and in between non-white space characters of the string.
#the string with white space characters
str = ' \n\tPython\n\tPool '
#strip any white space characters
strippedString = str.strip()
print("Original String\n~~~")
print(str)
print("\nStripped String\n~~~")
print(strippedString)
Output:
Original String ~~~ Python Pool Stripped String ~~~ Python Pool
Example 3: Python Program to Strip or Trim Strip Specified Character(s)
In this example, we will take a string and strip any character(s) that are present in the characters argument passed to strip().
#the string to trim
str = '---$Python Pool$-$'
characters = '-$'
#strip the string
strippedString = str.strip(characters)
print("Original String\n----")
print(str)
print("\nStripped String\n---")
print(strippedString)
Output:
Original String ---- ---$Python Pool$-$ Stripped String --- Python Pool
The characters – and $ and any if provided will be removed from the beginning and end of this string.
Point to Be Noted:
strip() function does not affect any white space between the non-white space characters. We will explain this in the following examples.
Python Trim Using rstrip() Trim Method
The rstrip method removes the trailing whitespace and returns the new string. In other words, it will remove the whitespace from the right side of the given string.
Syntax of Python Trim rstrip()
The syntax of the rstrip() function is:
string.rstrip(characters) |
Parameters of the rstrip() function in Python
Parameter characters
is optional.
If no argument is provided, then the white spaces from the right side of the string are deleted. All the combinations of the remove argument are deleted from the actual string until a mismatch occurs.
Example of rstrip() Python Trim
## Remove the Starting Spaces in Python using rstrip
mystring="Python Pool is the best place to learn python "
print (mystring)
print (mystring.rstrip())
rstrip() function in the above example strips the trailing space so the output will be
Output:
Python Pool is the best place to learn python ' Python Pool is the best place to learn python'
Python Trim Using lstrip() Trim Method
The lstrip method removes the leading whitespace and returns a new string. In other words, it will remove the whitespace from the left/beginning side of the given string.
Syntax of Python Trim lstrip()
The syntax of the lstrip() function is:
string.lstrip(characters) |
Parameters of the lstrip() function in Python
Parameter characters
is optional. The characters are trimmed from the left of the string until the initial mismatch occurs.
If no arguments are specified, all the whitespaces will be removed from the left side of the string.
Example of lstrip() Python Trim
## Remove the Starting Spaces in Python using lstrip
mystring=" Python Pool is the best place to learn python"
print (mystring)
print (mystring.lstrip())
lstrip() function in the above example strips the leading space so the output will be
Output:
Python Pool is the best place to learn python Python Pool is the best place to learn python
Using All Three Methods Together
name = ' Python Pool '
#remove spaces from left
print (name.lstrip())
#remove spaces from right
print (name.rstrip())
#remove spaces from both side
print (name.strip())
Output:
Python Pool Python Pool Python Pool
Which Whitespaces Does string.strip() remove?
The strip() method removes all whitespace characters when called without the optional argument. There are the most important whitespaces that are removed:
- space ‘ ‘
- newline characters ‘\n’
- carriage return ‘\r’
- horizontal tab ‘\t’
Note:
These three methods do not remove empty spaces between the strings and are usually used where the input is taken from the user
Conclusion
We learned the need for white spaces but also on how Python can help remove white spaces where they are not necessary. The strip(), lstrip() and rstrip() are some of the methods discussed. We also learned how to Python Trim a string according to our need.
If you still have any doubts do let us know in the comments.
Happy Coding!