Use s.replace("char", "") to remove every occurrence of a specific character from a string in Python—or use s.translate(str.maketrans("", "", "chars")) when stripping multiple distinct characters simultaneously in a single $O(n)$ pass, since Python strings are immutable and always return a new string.
Basic Example
text = "hello-world-2026"
# 1. Remove ALL occurrences of a single character using .replace()
clean_text = text.replace("-", "")
print(clean_text) # Output: "helloworld2026"
# 2. Remove ONLY the first 'n' occurrences by passing the optional count argument
first_removed = text.replace("-", "", 1)
print(first_removed) # Output: "helloworld-2026"
# 3. Remove MULTIPLE distinct characters at once using .translate()
messy = "(555) 123-4567"
digits_only = messy.translate(str.maketrans("", "", "()- "))
print(digits_only) # Output: "5551234567"
Key Details & Edge Cases
- Strings are immutable (
s.replace()does not modifysin place): Callingtext.replace("-", "")without assigning the result leavestextunchanged. Always reassign (text = text.replace("-", "")). - Removing a character at a specific index position: Because strings do not have
.pop()ordel s[i], remove a character at indexivia slicing:s = "Python" idx = 2 # Remove 't' result = s[:idx] + s[idx + 1:] print(result) # Output: "Pyhon" - Removing characters only from the start or end of a string (
.lstrip(),.rstrip(),.strip()):- If you only want to remove leading/trailing occurrences of a character without touching occurrences in the middle, use
.strip("char")(e.g.,"--hello-world--".strip("-")returns"hello-world"). - Beware:
.strip("abc")treats"abc"as a set of characters, not an exact substring prefix/suffix. To remove an exact prefix or suffix substring (Python 3.9+), use.removeprefix("sub")or.removesuffix("sub").
- If you only want to remove leading/trailing occurrences of a character without touching occurrences in the middle, use
- Why
str.translate()outperforms chained.replace()calls for multiple characters: Chainings.replace("a", "").replace("b", "").replace("c", "")allocates a brand-new string object on every call ($O(k \cdot n)$).s.translate(str.maketrans("", "", "abc"))executes in C in a single $O(n)$ scan. - Regex removal (
re.sub) for character classes: When removing categories of characters rather than fixed literals (such as all punctuation or all non-digits), usere.sub(r"[^\w\s]", "", text)orre.sub(r"\D", "", phone).
Comparison of Character Removal Methods in Python
| Method | Syntax | Time Complexity | Removes Multiple Distinct Chars? | Best Used When |
|---|---|---|---|---|
str.replace() |
s.replace("x", "") |
$O(n)$ (C-optimized) | Only via chaining | Removing all (or the first count) occurrences of a single character or substring. |
str.translate() |
s.translate(str.maketrans("", "", "xyz")) |
$O(n)$ single pass | Yes | Stripping a set of multiple characters (punctuation, delimiters, whitespace) efficiently. |
| String Slicing | s[:i] + s[i+1:] |
$O(n)$ | Single index | Removing a character at a known integer position i. |
str.strip() / lstrip() / rstrip() |
s.strip("-") |
$O(n)$ | Yes (edges only) | Trimming leading and/or trailing occurrences of specific characters. |
re.sub() |
re.sub(r"[aeiou]", "", s) |
$O(n)$ (regex engine) | Yes (pattern-based) | Removing characters matching a pattern or Unicode character class. |
You must log in or register to comment.
