HOWTO · Python

How to Remove Certain Characters From String in Python

Learn how to remove selected characters or patterns from a Python string with str.replace(), str.translate(), filtering, and re.sub().

On this page

Use str.replace() to remove a known substring, str.translate() to delete several individual characters, a comprehension to keep characters that meet a condition, or re.sub() when the characters are described by a pattern. Each approach returns a new string: Python strings are immutable, so the original value remains available. All four examples below were executed successfully, and each printed Hello World.

Remove selected characters with str.replace()

str.replace(old, new) replaces occurrences of one substring with another. Use "" as the replacement to delete it. This is clear when the targets are known and few; repeated calls can handle a small set.

This example removes two known substrings from a greeting:

source = "Hello, World!"
cleaned = source.replace(",", "").replace("!", "")
print(cleaned)

The calls remove commas and exclamation marks wherever they occur. They do not change source; assign the returned value if later code should use the cleaned text. replace() also removes longer known substrings, so use it when the target is a word or sequence, not only a single character. For a longer list of individual characters, a translation table or filter is easier to maintain.

Remove multiple characters with str.translate()

Use str.maketrans() with its third argument to build a deletion table for a set of individual characters. Then pass the table to str.translate(). Each character listed for deletion is removed wherever it appears; this does not match arbitrary multi-character substrings.

source = "Hello, World!"
remove_chars = ",!"
table = str.maketrans("", "", remove_chars)
cleaned = source.translate(table)
print(cleaned)

Change remove_chars to control which characters disappear. This is a useful fit when the rule is a fixed collection of characters. str.maketrans() can also describe character replacements, but the third argument specifically marks characters for deletion. For a rule based on a condition, use filtering instead.

Filter characters and join the result

A comprehension makes the keep-rule visible: iterate over the input and retain a character only when it is not in the removal set. Then call str.join() on the separator string to combine the retained characters. The empty separator shown here concatenates them with no added text.

source = "Hello, World!"
remove_chars = set(",!")
cleaned = "".join(char for char in source if char not in remove_chars)
print(cleaned)

Use a condition that expresses what should remain, such as keeping only digits with char.isdigit(). The condition is evaluated for each character, so it can encode rules that are more flexible than a fixed deletion table. The separator controls the result: " ".join(...) inserts spaces between retained items, while "".join(...) puts adjacent characters together. join() combines an iterable; it does not perform the filtering itself.

Remove characters that match a pattern with re.sub()

re.sub(pattern, replacement, text) replaces every match of a regular-expression pattern. A character class lists alternatives to match one character at a time, and an empty replacement deletes each match. Use a raw string for patterns when it helps keep backslashes readable.

import re

source = "Hello, World!"
cleaned = re.sub(r"[,!]", "", source)
print(cleaned)

The class [,!] matches a comma or an exclamation mark. To remove a range or a category of characters, express that rule in the pattern; read and test such patterns carefully because punctuation can have special meaning in regular expressions. Escape a character when it should be matched literally but has a regex role. For a short fixed set, str.translate() is often easier to read; choose re.sub() when pattern matching is the point.

Choose an approach and understand its limits

Choose based on how the unwanted text is specified:

  • Use str.replace() for one known substring or a few explicit substitutions.
  • Use str.translate() for deleting a fixed set of individual characters.
  • Use a comprehension and str.join() when the rule is a condition on each character.
  • Use re.sub() when a regular-expression pattern describes what to remove.

These operations remove exactly what their arguments select. They do not automatically trim surrounding whitespace, normalize Unicode, or treat uppercase and lowercase letters as equivalent. If removal should ignore case, define which case variants to match or apply a case-insensitive matching rule, and consider that converting the source text to lower or upper case changes the text itself. Avoid converting it solely to remove characters unless that change is desired. The examples illustrate each method’s shape; no relative speed claim is needed to choose among them. Prefer the clearest rule for the data being cleaned, then measure with representative input if performance matters.