You can trim string in python using a strip() function. It removes the leading and trailing spaces of a given String. There are 2 more methods “lstrip() and rstrip()” that can use to remove leading or trailing whitespaces.
Note: default whitespace characters will remove, you can remove other char also.
Method to trim Strings in Python
- strip(): removes spaces from the left and right of the string and returns the copy of the string.
- lstrip(): returns the string after removing leading whitespaces.
- rstrip(): returns a string after removing the trailing whitespace
Syntax
string.strip([remove]) # OR str.strip([chars])
Parameters
The characters are to be removed from the beginning or end of the string.
Python strip() example | trim string
Let’s see examples of how to trim strings from left, right, or all whitespaces.
1. Without chars parameter
The below code displays the working of strip() in various conditions.
str1 = " Hello World! " # Original String print(str1) # Remove all space print(str1.strip()) # left Whitespace print(str1.lstrip()) # Right Whitespace print(str1.rstrip())
Output: Blue color space indicates whitespace.
2. Remove “0” from String
str1 = "0000this is string trim example....!0000" print(str1.strip('0'))
Output: this is string trim example….!
3. trim a string from Left | lstrip() Python
USE “lstrip() function” to remove left space from sting.
str.lstrip([chars])
Example
s = " Python lstrip method " print(s.lstrip())
Output: Python lstrip method
4. trim a string from Right | rstrip() Python
The rstrip() method removes the trailing (right) spaces from the given string and returns a copy after removing whitespaces from the right side.
str.rstrip([chars])
Example
s = " Python rstrip method " print(s.rstrip())
Output: Python rstrip method
Q: How to trim string characters in Python?
Answer: Remove ‘www’ and ‘com’ and ‘.’ from the string using a strip() method.
string = 'www.EyeHunts.com' # '.comw' removes 'www' and 'com' and '.' print(string.strip('.comw'))
Output: EyeHunts
Q: How to trim all whitespace include between text in python?
Answer: If you noticed the strip method only remove the left and right space or char. So if you want to remove all space from a string you can use replace() method in Python.
s = ' a b c d ' print(s.replace(" ", ""))
Output: abcd
Read More about – Python string replace function Examples
Do comment if you knew any other way to do it. Or have any suggestions Or doubts.
Note:
IDE: PyCharm 2020.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples string.count python 3, so it may change its different from python 2 or upgraded versions.