Python provides a special 3 methods to remove whitespace from a string (characters)
- lstrip() – Remove spaces to the left of the string
- rstrip() – Remove spaces to the right of the string
- strip() – Remove spaces at the beginning and at the end of the string.
There are 2 more methods used in Python to remove single or multiple characters from the string as well. For example,
- translate() – specified characters are replaced with the character described in a dictionary, or in a mapping table
- replace() – replaces a specified phrase with another specified phrase.
Example strip multiple characters in Python
Simple example code.
Strip Multiple Characters in Python
To strip multiple characters in Python, use the string strip() method. It removes the whitespace from the beginning and end of the string by default. But this method also takes an argument. You have to pass the character in the method and it will remove it.
It will remove characters from both ends.
str1 = "Hello Python DeveloperHe"
strippedString = str1.strip("He")
print(strippedString)
Output:
Using replace()
This method replaces a character with a new character.
str1 = "Hello Python HeDeveloperHe"
strippedString = str1.replace("He", "")
print(strippedString)
Using RegEx
import re
print(re.sub("e|l", "", "Hello people"))
"Ho pop"
strip characters from string python regex
import re
phone = "2004-959-559 # This is Phone Number"
# Delete Python-style comments
num = re.sub(r'#.*$', "", phone)
print("Phone Num : ", num)
# Remove anything other than digits
num = re.sub(r'\D', "", phone)
print("Phone Num : ", num)
Output:
Do comment if you have any doubts or suggestions on this Python char example.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.