In this article, we will discuss different ways to remove specific characters from a string in python.

For example, we have a string,

sample_str = 'This is& is a#@ sample! string is :,'

And we want to delete all occurrences of some specific characters from the string. These specific characters are,

  • ‘&’
  • ‘#’
  • ‘@’
  • ‘!’
  • ‘;’
  • ‘,’
  • ‘:’
  • ‘\”

After removing these specific characters from string, our output string should be like,

This is is a sample string is

It might be possible that you want some other characters to be removed from the string. Therefore the solutions which we are going to discuss here can work with any other characters too.

Before diving into the solutions, we need to understand that, in Python strings are immutable. It means, once the string object is created then we can not modify it. But we can always create a new string with by copying only few characters from the original string and assign it back to original variable. It will give an effect that we have modified the original string.

So, let’s start discussing the different techniques to delete specific characters from a string,

Python: Remove specific characters from a string using translate()

In python, string class provides a member function translate(mapping_table). It accepts a mapping table as an argument. Based on the character mappings in table, it replaces the characters in the string. If in the translate() function, we pass a mapping table, in which some specific characters are mapped to an empty string, then translate() function deletes those characters from the string.

So, to delete some specific characters from a string, follow these steps,

  • Create a mapping record / translation table, where each of the character to be deleted is mapped to an empty string.
  • Pass this translation table to translate() function. It will remove these characters from the string.

Let’s see an example where we will delete following characters ‘&#@!;,:’ from the string using translate() function,

# String that need to be modified
sample_str = 'This is& is a#@ sample! string is :,'

# Characters, that needs to be deleted from the another string.
chars_to_be_removed = '&#@!;,:'

# Map characters to be deleted with an empty string
translation_table = str.maketrans('', '', chars_to_be_removed)

# Remove specific characters from the string based
# on translation table / mapping table
sample_str = sample_str.translate(translation_table)

print(sample_str)

Output:

This is is a sample string is

It deleted all the occurrences of specified characters from the string.

Python: Remove specific characters from a string using regex

Python’s regex module provides a function sub() i.e.

re.sub(pattern, repl, string, count=0, flags=0)

It returns a new string. This new string is obtained by replacing all the occurrences of the given pattern in the string by a replacement string repl. If the pattern is not found in the string, then it returns the same string. We can use this to delete specific characters from a string in python,

  • Create a regex pattern that matches all occurrences of the specified characters in string.
  • Pass this pattern to the res.sub() function with an empty string as replacement. It will remove these specific characters from the string.

Let’s see an example where will delete following characters ‘&#@!;,:’ from the string using regex

import re

# String that need to be modified
sample_str = 'This is& is a#@ sample! string is :,'

# Characters, that needs to be deleted from the another string.
chars_to_be_removed = r'&#@!;,:'

pattern = '[' +  chars_to_be_removed +  ']'

# Remove specific characters from the string that matches the regex pattern
sample_str = re.sub(pattern, '', sample_str)

print(sample_str)

Output:

This is is a sample string is

Here we passed a pattern r'[&#@!;,:]’ & an empty string as replacement string to the sub() function. This pattern matched all the given characters in the original string and sub() function replaced all the matched characters by an empty string. So, this is how we can delete all the occurrences of specified characters from a string in python.

Python: Remove specific characters from a string using replace() function

In python, string class provides a member function replace() i.e.

replace(str_to_replace, replacement)

It returns a copy of the calling string object, after replacing all occurrences of the given substring with the replacement string. We can use this to delete specific characters from a string in python. For example,

sample_str = 'This is& is a#@ sample! string is :,'

# Characters, that needs to be deleted from the another string.
chars_to_be_removed = '&#@!;,:'

# Remove specific characters from the string
for character in chars_to_be_removed:
    sample_str = sample_str.replace(character, '')

print(sample_str)

Output:

This is is a sample string is

We iterated over all the characters that needs to be deleted from string and one by one, we replaced the all occurrences of characters with an empty string.

Remove specific characters from string using filter() & join()

Filter all the occurrences of specific characters from a string and join the remaining characters to create a new string i.e.

sample_str = 'This is& is a#@ sample! string is :,'

# Characters, that needs to be deleted from the another string.
chars_to_be_removed = '&#@!;,:'

# Filter all digits from characters in string and create list of remaining chars
filtered_chars = filter(lambda item: item not in chars_to_be_removed, sample_str)

# Join characters in the filtered list
sample_str = ''.join(filtered_chars)

print(sample_str)

Output:

This is is a sample string is

It deleted all given characters from the string.

How did it worked?

We passed a lambda function and original string to the filter() function. Then the filter() function iterated over all characters in string and called the given lambda function on each character. The filter() function yielded those characters for which the lambda function returned True. Then we joined back all those filtered characters to create a
new string. So, basically first we filtered all the specified characters from a string and then joined all the remaining characters.

Summary

We learned about different ways to remove specific characters from a string in python.