










To remove characters from a string in Python, build a new string because
str objects are immutable. Use str.replace() for a single character or
substring, str.translate() or str.maketrans() to drop several characters in
one pass, re.sub() for pattern-based removal, and slicing when you need to
remove characters at the start, end, or a fixed index.
This tutorial walks through each approach with runnable examples in the Python interactive console. For whitespace-only cleanup, see Remove Spaces from a String in Python.
Deploy your Python applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.
replace(old, '') for one character or substring; pass a third
argument to limit how many replacements run.translate() with str.maketrans('', '', chars) or a mapping dict to
remove several characters in a single pass.re.sub() when removal depends on a pattern (digits, punctuation,
non-ASCII).s[1:], s[:-1], s[:i] + s[i+1:]) to drop the first,
last, or indexed character without scanning the whole string.strip(), lstrip(), and rstrip() remove leading or trailing
characters (often whitespace), not arbitrary characters in the middle.remove(); strings do not—calling remove() on a string
raises AttributeError.| Method | Best for | Limitation |
|---|---|---|
replace() |
One character or substring; simple literals | Multiple different chars need chained calls or a loop |
translate() / maketrans() |
Many distinct characters at once | Less readable for complex patterns |
re.sub() |
Digits, punctuation classes, regex rules | Slower than replace() for a single literal |
| Slicing | First, last, or index-based removal | Not for “remove all a” across the string |
strip() / lstrip() / rstrip() |
Leading or trailing junk (spaces, \n) |
Does not touch characters in the middle |
replace()str.replace() returns a copy of the string with each occurrence of the
first argument replaced by the second. Pass an empty string as the second
argument to delete matches.
Declare a sample string:
- s = 'abc12321cba'
Remove every a:
- print(s.replace('a', ''))
Output:
Output
bc12321cb
Both a characters are gone; the original s is still 'abc12321cba'.
- s = 'ab\ncd\nef'
- print(s.replace('\n', ''))
Output:
Output
abcdef
- print('Helloabc'.replace('Hello', ''))
Output:
Output
abc
The optional third argument caps replacements:
- print('abababab'.replace('a', 'A', 2))
Output:
Output
AbAbabab
Only the first two a characters change. See
Python String replace()
for more detail.
translate()str.translate() maps each character through a table. Map unwanted
characters to None (or use str.maketrans with a delete set) to remove them.
Remove every b:
- s = 'abc12321cba'
- print(s.translate({ord('b'): None}))
Output:
Output
ac12321ca
Remove several characters in one call:
- print(s.translate({ord(i): None for i in 'abc'}))
Output:
Output
12321
The same idiom works for newlines:
- print('ab\ncd\nef'.translate({ord('\n'): None}))
Output:
Output
abcdef
str.maketrans('', '', ',!') builds a delete-only table that is often
easier to read than a dict comprehension:
string = "Hello, World!"
print(string.translate(str.maketrans("", "", ",!")))
# Hello World
re.sub() fits when the rule is a pattern, not a fixed literal. Import
re first.
Remove digits:
import re
text = "Hello123 World456"
print(re.sub(r'\d+', '', text))
# Hello World
Remove non-alphanumeric characters:
print(re.sub(r'[^a-zA-Z0-9]', '', "Hello, World! 123"))
# HelloWorld123
Strip non-ASCII characters:
raw = 'Café résumé'
print(re.sub(r'[^\x00-\x7F]+', '', raw))
# Caf rsum
For a focused guide on pattern syntax, see Python Regular Expressions.
Slicing drops characters by position without searching the whole string.
s = "Hello, World!"
print(s[1:]) # ello, World! — remove first character
print(s[:-1]) # Hello, World — remove last character
i = 4
print(s[:i] + s[i+1:]) # Hell, World! — remove character at index i
A list comprehension (or generator inside join) filters characters:
vowels = 'aeiouAEIOU'
print(''.join(c for c in 'hello world' if c not in vowels))
# hll wrld
On a million-character test string (Python 3.12, local run), rough timings were:
| Task | Fastest approach |
|---|---|
| Remove one repeated character | replace() |
| Remove several different characters | translate() or one re.sub('[abc]', '') |
| Pattern-based cleanup | re.sub() |
Chaining several replace() calls on huge strings costs more than one
translate() or a single regex. For typical application strings, any of these
methods is fast enough—profile only when you process megabytes per request.
In data workflows, apply string methods per column.
Keep only digits with .str.replace() and a capture group:
import pandas as pd
df = pd.DataFrame({'strings': ['123abc', '456def', '789ghi']})
df['strings'] = df['strings'].str.extract(r'(\d+)')[0]
print(df)
Custom filter with .apply():
def remove_vowels(text):
vowels = 'aeiouAEIOU'
return ''.join(c for c in text if c not in vowels)
df = pd.DataFrame({'strings': ['hello world', 'python is fun']})
df['strings'] = df['strings'].apply(remove_vowels)
See the Pandas module tutorial for broader DataFrame string operations.
Call replace() with an empty replacement string:
text = "Hello, World!"
print(text.replace(",", ""))
# Hello World!
For many different characters, prefer translate() or re.sub() so
you do not chain dozens of replace() calls.
remove() method for strings in Python?No. list.remove() deletes an item from a list, but strings have no
remove() method. Using "abc".remove("a") raises AttributeError. For
strings, use replace(), translate(), re.sub(), or slicing.
Use slicing to skip the index you do not want:
s = "EXAMPLE"
i = 2 # remove 'A' at index 2
print(s[:i] + s[i+1:])
# EXMPLE
To remove every occurrence of a character regardless of position, use
replace() or translate(), not index slicing.
strip() in Python, and when should I use it?strip() removes leading and trailing characters (default: whitespace).
Variants lstrip() and rstrip() trim one side only. They do not
remove characters from the middle of a string. Use strip() after reading
lines from a file; use replace('\n', '') or translate() when newlines
appear anywhere in the text. Compare with
Trimming a String in Python.
Option 1 — translate() (one pass):
s = "a1b2c3"
print(s.translate(str.maketrans("", "", "abc")))
# 123
Option 2 — re.sub() (pattern):
import re
print(re.sub(r'[abc]', '', s))
# 123
Option 3 — loop with replace() (readable for a short list):
for ch in "abc":
s = s.replace(ch, "")
For two or three characters, a loop is fine. For longer delete sets,
translate() or regex is usually clearer and faster on large inputs.
You can remove characters from Python strings with replace() for
literals, translate() for batches of characters, re.sub() for
patterns, and slicing for positional edits. Pick the tool that matches your
rule set, remember that strings are immutable, and return a new value to the
caller.
Continue with Python string functions, converting a string to a list, and removing spaces from a string.
Deploy Python apps from GitHub with DigitalOcean App Platform and keep building on the Gen AI Platform when your project needs managed inference.
This work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。