How do you remove a specific character from a string in Python? | A1Lab@MZeeshanM to PythonEnglish • 5 days ago

How do you remove a specific character from a string in Python?

message-square
0

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 modify s in place): Calling text.replace("-", "") without assigning the result leaves text unchanged. Always reassign (text = text.replace("-", "")).
  • Removing a character at a specific index position: Because strings do not have .pop() or del s[i], remove a character at index i via 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").
  • Why str.translate() outperforms chained .replace() calls for multiple characters: Chaining s.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), use re.sub(r"[^\w\s]", "", text) or re.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.