Remove multiple characters from string Python (9 Methods)

In this Python tutorial, I will explain how to remove multiple characters from String Python using different methods and some demonstrative examples. Here, I will show how to remove a character from a Python string and how to remove the first or last characters in Python.

A Python string is a data type used to represent text. It is an immutable sequence of Unicode characters. Strings can be created by enclosing text in single (‘ ‘), double (” “), or triple (”’ ”’ or “”” “””) quotes.

String1 = 'Welcome to PythonGuides!'
String2 = "Hello, Programmer!"
String3 = '''Hello,
Programmer!'''
String4 = """Hello,
Programmer!"""

print(type(String1))
print(type(String2))
print(type(String3))
print(type(String4))

Output: Checking the types of each variable we have created.

<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
remove function in python string

All the variables we have created are of string data type in Python.

While it’s true that strings in Python are immutable (meaning we can’t change an existing string in place), we can always create a new string that represents the desired modification of the original string.

Here are some methods to “remove” characters from a string in Python, bearing in mind that each method returns a new string and leaves the original string unchanged.

Methods to Remove multiple characters from string Python

There are several different methods present in Python to remove multiple characters from string Python:

  • Using String slicing
  • Using for loop
  • Using replace() function
  • Using List comprehension
  • Using str.translate()
  • Using Regular Expressions
  • Using the split() and join() methods
  • Using the filter() function
  • Using strip() function

Let’s see them one by one using illustrative examples:

Method 1: Python remove multiple characters from string using String slicing

String slicing in Python allows us to extract parts of a string based on indices.

The string slicing syntax in Python is:

string[start:stop:step]
NameDescription
StartThe beginning index of the slice. Its default value is 0.
StopThe slice goes up to but does not include, this index. Its default value is the end of the string.
StepThe number of indices between items in the slice. Its default value is 1.
List of parameters in string slicing in Python.

To remove specific characters using slicing, we typically concatenate slices that skip over the undesired characters.

Case 1: Python remove a character from string using string slicing

If we know the index of the character we wish to remove, we can do so by concatenating two slices: one slice before the undesired character and one slice after in the Python string.

For instance, Let’s consider a scenario where we have a string in Python that represents the ZIP code for a location in the USA. ZIP codes in the USA are typically 5 digits long.

For this example, let’s say we want to remove the hyphen (-) from the ZIP+4 format to make it a continuous 9-digit number.

zip_code = "12345-6789"
new_zip = zip_code[:5] + zip_code[6:]
print(new_zip)

Output: In this Python string, the hyphen is at the 5th position (remember, Python uses 0-based indexing). To remove the hyphen, we can take all characters before it and all characters after it, then concatenate them together. By concatenating these two substrings, we effectively remove the hyphen.

123456789
Python remove a character from string

This way we can use the string slicing method to remove multiple characters from string Python.

READ:  How to replace multiple spaces with a single space in Python [3 Methods]

Case 2: Python delete multiple characters from string at Known Positions

To remove multiple characters from string Python, we can create multiple slices that “jump” over each undesired character and then concatenate these slices together. Each slice captures the parts of the Python string in Python we wish to keep.

For example, Let’s say we have a phone number like “(123) – 456 – 7890”, and we want to remove the extra spaces and dashes to get it in the desired format (123) 456-7890.

Phone_number = "(123) - 456 - 7890"

formatted_number = Phone_number[1:4] + Phone_number[8:11] + Phone_number[14:]
print(formatted_number)

Output: In the example, we used Python string slicing to retain the parts of the original string in Python that we wanted and skip over the unwanted characters.

1234567890
remove character from string python

This way we can remove multiple characters from string Python using string slicing.

Method 2: How to remove multiple characters from a string in Python using for loop

Removing multiple characters from a string using a for loop typically involves iterating over the string and checking each character to determine whether it should be kept or discarded. After the determination, we can construct a new string with the desired characters.

Example: At a tech company’s annual Hackathon event, programmers are encouraged to come up with small, fun projects to showcase their skills. So, we decided to create a program that removes vowels from the string stored in Python.

s = "Hello, welcome to PythonGuides.com"
chars_to_remove = "aeiou"
new_str = ""

for char in s:
    if char not in chars_to_remove:
        new_str += char
print(new_str)

Output: We are using a for loop to iterate over the string and then using a conditional statement we check for the vowels.

Hll, wlcm t PythnGds.cm
Python remove two characters from string

This way we use a for loop to remove multiple characters from String Python.

Method 3: Python remove multiple characters from a string using replace() method

The replace() method in Python is used to replace a substring of a string with another substring. The basic syntax of this method is:

string.replace(old, new, count)
NameDescription
OldIt is the substring which, we want to replace.
NewIt is the substring that we will replace with old.
Count(optional) is the maximum number of occurrences to replace. If omitted or None, all occurrences will be replaced.
List of parameters in replace() method in Python.

However, the replace() method is designed to replace one substring at a time. If we want to remove multiple characters (or substrings) from a string in Python using replace(), we’ll have to call this method multiple times, either using chained calls or through iteration.

Example: Imagine we’ve extracted text from a website about the most popular tourist destinations in the USA. However, due to some formatting issues during extraction, certain unwanted symbols or characters have been included. Our task is to clean up this text.

text = "The top destinations in the USA are: [New York City], {Los Angeles}, <San Francisco> and, |Miami|."
chars_to_remove = ['[', ']', '{', '}', '<', '>', '|']
for char in chars_to_remove:
    text = text.replace(char, '')
print(text)

Output: We notice that city names are surrounded by unwanted characters: [ ], { }, < >, and | | and we have to remove these multiple characters from this Python string. Starting with the initial string, we iterate over our list of characters to remove.

The top destinations in the USA are: New York City, Los Angeles, San Francisco and, Miami.
Python remove a character from a string using replace() method

This way we can use the replace() method to remove multiple characters from string Python.

Method 4: Using List comprehension in Python to remove character from string

The process of using list comprehension to remove characters involves breaking the Python string down into a list of characters, filtering out the undesired characters with a list comprehension, and then reassembling the string in Python.

For instance, Imagine we’re preparing a report on the list of U.S. states that participated in a particular survey. We receive the list in a Python string, but unfortunately, the string contains some unwanted characters (like numbers and special symbols). We need to remove these extraneous characters to have a clear list of states through the Python Program.

States = "Califor1nia, Nev*ada, 3Oregon, 45Utah, Ar#izona"

list_of_chars = [char for char in States]
filtered_chars = [char for char in list_of_chars if char.isalpha() or char == ' ' or char == ',']
clean_states_list = ''.join(filtered_chars)

print(clean_states_list)

Output: We’ll use Python’s str.isalpha() method, which returns True if the character is a letter and False otherwise. We’ll also allow spaces and commas, so the states remain separated.

READ:  Python Increment Value in Dictionary

Using list comprehension, we iterated over each character of the original string. We filtered out unwanted characters by ensuring that each character in the new list is either a letter, a space, or a comma. Finally, we used the join() method to concatenate the list of filtered characters back into a clean string.

California, Nevada, Oregon, Utah, Arizona
Remove multiple characters from a string in python

This way we can remove multiple characters from string Python using list comprehension with isalpha() function, and join() function.

Method 5: Python remove a character from a string using translate() method

The translate() method of strings in Python is a powerful tool to perform character-level transformations, and in combination with the maketrans() function, it becomes a versatile method for character removal and substitution.

The translate() method returns a string where some specified characters are replaced with the characters described in a translation table. This translation table is usually created using the str.maketrans() method. It can take up to three arguments:

NameDescription
xIf only one argument is supplied, it must be a dictionary with Unicode ordinals (integer values) as keys and their replacement as values.
x and yIf two arguments are supplied, they must be strings with equal length. Each character in x will be replaced by the character at the same position in y.
x, y, and zIf three arguments are supplied, each character in the third argument z is mapped to None.
List of arguments taken by str.maketrans() method in Python.

For instance, Imagine we have a string in Python that represents a list of movies and their box office collections in millions. The list is represented as comma-separated pairs of movie names and their box office collections.

However, for some reason, the dollar sign ($) and commas (,) have been included in the box office collections. Our goal is to remove these unnecessary characters to make it easier to process the numbers.

movies_data = "The Avengers $1,234.56m, Star Wars: The Force Awakens $987,654.32m"
remove_chars = "$,"
translation_table = str.maketrans('', '', remove_chars)
cleaned_data = movies_data.translate(translation_table)
print(cleaned_data)

Output: We have a Python string remove_chars that contains the characters we want to remove, which are the ($) and (,). We use str.maketrans(”, ”, remove_chars) to create a translation table. This table essentially maps the characters ($) and (,) to None.

We then call translate() on our movies_data string, passing the translation table. This will return a new string with the specified characters removed in Python.

The Avengers 1234.56m Star Wars: The Force Awakens 987654.32m
Python remove multiple characters from a string using translate() method

This way we can use str.translate() with str.maketrans() method to remove multiple characters from string Python.

Method 6: How to Remove multiple characters from a String Python using Regular Expression

Regular expressions are a powerful tool for text processing. They allow for pattern matching and complex string manipulations in Python.

In Python, the re module provides functions and classes for working with regular expressions. One of the most commonly used functions from the re module is re.sub(), which replaces substrings that match a specified pattern.

For example, We’re managing customer feedback for a tech store in Silicon Valley through Python. Sometimes, customers reference local area codes “408” and “650” in their comments. For privacy, we decided to remove these area code references before publishing the feedback.

import re

feedback = "The product is great. But can you call me back at 408?\nI had issues with the device. My area code is 650."
filtered_feedback = re.sub('408|650', '', feedback)
print(filtered_feedback)

Output:

The product is great. But can you call me back at ?
I had issues with the device. My area code is .
Python remove a character from string regex

This way we can use the sub() function from the regex module to remove multiple characters from a string in Python.

READ:  How to split a string with multiple delimiters in Python

Method 7: Use the split() and join() methods to Python remove multiple character from string

The split() method is primarily used to divide a string based on a specified delimiter. It returns a list of substrings in Python. And, the join() method is a string method that takes a list of strings and joins them into a single string in Python.

For example, Imagine we own a chain of restaurants across the USA. We gather customer feedback through online reviews. These reviews are stored in strings in Python and often contain extraneous punctuation that we’d like to remove to analyze the text more easily.

def clean_review(review):
    chars_to_remove = ['!', '?', '.']
    for char in chars_to_remove:
        review = ''.join(review.split(char))
    return review
review = "The burger was amazing! However, the service was slow. Would visit again?"
cleaned_review = clean_review(review)
print(cleaned_review)

Output: The operation of removing iterate over all the characters in the string and at the end everything is joined together as a new string in Python.

The burger was amazing However, the service was slow Would visit again
python string remove multiple characters

This way we can use split() and join() functions to remove multiple characters from string Python.

Method 8: Remove multiple characters from String using filter() function in Python

The filter() function in Python allows for filtering elements of an iterable based on a function that returns True or False. For Python strings, this can be used to filter out (or keep) specific characters.

For instance, Imagine we’re working with the Department of Motor Vehicles (DMV) in the USA. The DMV provides us with a list of license plates in Python, but due to a system error, some of the license plates have undesirable characters (*, #, &, and @). We’re tasked with cleaning up these license plates through Python.

def remove_unwanted_chars(plate):
    unwanted_chars = ['*', '#', '&', '@']
    return ''.join(filter(lambda char: char not in unwanted_chars, plate))

license_plate = "AB*#12@34"
cleaned_license_plate = remove_unwanted_chars(license_plate)
print(cleaned_license_plate)

Output: In this example, We have created a lambda function that will check every character within the string, then the filter() function will filter all the verified characters and at last, the join() function will join all the characters of the string in one string.

AB1234
remove multiple character from string python

This way we can use the filter() function to remove multiple characters from Python string.

Method 9: Python strip multiple characters from string

In Python, the strip() method is primarily used to remove leading and trailing characters (whitespaces by default) from a Python string. However, the strip() function can also be used to remove other leading and trailing characters by specifying the set of characters to be removed.

Case 1: Using only strip() function to Remove letter from string Python

In this case, we will remove the characters from the first and last of the string in Python. And, we can use the split() function to remove multiple characters from string Python

For example, Imagine we are handling data from an old database, and state names in addresses are stored within two bars(|) and other special characters. Like, New York is represented as *#*|NY|*#. And, we want to remove these bars(|) and other special characters.

address_old_format = "*#*|NY|*#"
cleaned_address = address_old_format.strip('*#|')
print(cleaned_address)

Output: The characters are removed from both sides of the Python string.

NY
python remove characters from string

This way we can use the split() function to remove multiple characters from Python string.

Case 2: Python strip first two characters of the string using lstrip() function

The lstrip() function is designed to remove all occurrences of specified characters from the left side of a string until it encounters a character not in the set provided in Python. It doesn’t remove a specific number of characters unless those characters match the set given.

For instance, Imagine we’re working with a list of ISBN numbers of books in a U.S. library database through Python. This library uses a unique system where U.S.-based authors’ ISBN numbers start with “US”, followed by the actual ISBN. We need to remove the “US” prefix from the ISBN numbers but only if they exist.

isbn_with_prefix = "US1234567890"
isbn_without_prefix = isbn_with_prefix.lstrip("US")
print(isbn_without_prefix)

Output: In this, we have simply used the lstrip() function in Python to remove characters from string Python.

1234567890
remove two characters from string python

This way we can remove the first 2 characters from the string in Python using the lstrip() function.

Case 3: Python strip last two characters using rstrip() function

The rstrip() function is used to remove trailing characters from the right side of a string in Python.

For example, In some Databases, the ZIP Codes have been mistakenly entered with an additional two-letter state abbreviation appended to the end, and we want to remove these last two characters when they’re letters.

def clean_zip(zip_code):
    if zip_code[-2:].isalpha():
        return zip_code.rstrip(zip_code[-2:])
    return zip_code

zip_with_state = "12345NY"
cleaned_zip = clean_zip(zip_with_state)
print(cleaned_zip)

Output: Here, we are defining a function(clean_zip) in Python where we will remove multiple characters from string Python. We are using the if conditional statement with string slicing and the isalpha() function.

12345
Python replace multiple characters in a string

This way we can use the rstrip() function to remove the last two characters from a string in Python.

Conclusion

Understanding how to remove multiple characters from string Python using different methods like String slicing, for loop, replace() function, List comprehension, str.translate() with str.maketrans(), sub() function in regular expression module, the split() with join() methods, filter() function, and strip() function with illustrative examples.

The choice depends on the specific use case and the programmer’s preference. Python offers flexibility and efficiency in removing multiple characters from a string.

You may also like to read: