Sr Technical Content Strategist and Team Lead
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:
Outputbc12321cb
Both a characters are gone; the original s is still 'abc12321cba'.
- s = 'ab\ncd\nef'
- print(s.replace('\n', ''))
Output:
Outputabcdef
- print('Helloabc'.replace('Hello', ''))
Output:
Outputabc
The optional third argument caps replacements:
- print('abababab'.replace('a', 'A', 2))
Output:
OutputAbAbabab
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:
Outputac12321ca
Remove several characters in one call:
- print(s.translate({ord(i): None for i in 'abc'}))
Output:
Output12321
The same idiom works for newlines:
- print('ab\ncd\nef'.translate({ord('\n'): None}))
Output:
Outputabcdef
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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer(Team Lead) @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix
Why do you copy standard library’s doc? What’s the point? You won’t teach anybody that way. One can read the documentation 10 times, learn everything about oop, functions, types, loops, etc and won’t be able to write two useful lines of code. Do you know why?
- MIllena
Can you please add the third argument replace() can take, which is the number of times the character will be replaced if there are multiple instances of the character within the string? I’m a beginner in python and I was trying to remove a character from a string but only a certain amount of times, not all instances. When I searched google, your article was the top result. But I had to browse several stack overflow threads to get the information. If you add it to your article, you might just make it easy for the next beginner in python.
- Joy
i want to remove only first char from a string but in this its remove all char related to that… for an example “helloworld” this is string i want remove only first “h” from string “helloworld”
- Prakash choudhary
Pankaj , your article was nice, but i stuck in solving same kind of problem. Can you help me. I have a dataset and i want to remove certain character from column. Column datatype is object. I am giving you example below- Mileage 21.6 km/kg 18.2 kmpl and so on, I have number of values. I want to remove km/kg and kmpl from the columns values. How can i do that. Thanks & Regards Ajay
- AJAY
Sir ,it removes all the character. For eg: If I remove ‘i’ in ‘initial’. It’s output is ‘ntal’.(it removes all ‘i’ in the string
- Shankar
i want to replace lowercase characters before and after key in given string “there is A key to Success”
- vrushali ingulkar
Hi, I have list of tuple. From that I want to remove few characters from tuple. Please check the below example: x = [(‘url/user/123’, ‘url/site/2’), (‘url/user/125’, ‘url/site/5’)] expected result: [(‘123’, ‘2’), [(‘125’, ‘5’)]]
- Ash
HI @Pankaj i want to replace or remove some variable from string that should not be print in after execution it should remove couple multi variable not only one variable so how can i do that Ex:-- from a input string we need to remove set of variable and need to print after removing it. so how can i do it i have tried with replace and TRAN but its not working. so help me out.
- ibrahim
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.