How to strip multiple characters Python | Example code

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,

  1. translate() – specified characters are replaced with the character described in a dictionary, or in a mapping table
  2. 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:

strip multiple characters Python

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:

strip characters from string python regex

Do comment if you have any doubts or suggestions on this Python char example.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.