Remove Characters from a String in Python

To remove characters from a string in Python, create a new string because str objects cannot be modified after they are created. Use str.replace() when removing a single character or substring, str.translate() or str.maketrans() when deleting several characters in one operation, re.sub() for pattern-based removal, and slicing when characters must be removed from the beginning, end, or a specific index.

This tutorial explains each method with runnable examples in the Python interactive console. For cleanup that only involves whitespace, see Remove Spaces from a String in Python.

Deploy Python applications from GitHub with a managed application platform and let the platform handle application scaling.

Key Takeaways

  • Python strings are immutable: removing characters always produces a new string, while the original string remains unchanged.
  • Use replace(old, '') for one character or substring. A third argument can be supplied to restrict the number of replacements.
  • Use translate() together with str.maketrans('', '', chars) or a mapping dictionary to delete multiple characters in one pass.
  • Use re.sub() when the removal rule is based on a pattern, such as digits, punctuation, or non-ASCII characters.
  • Use slicing, including s[1:], s[:-1], or s[:i] + s[i+1:], when removing the first, last, or indexed character without searching through the entire string.
  • strip(), lstrip(), and rstrip() delete characters at the beginning or end of a string, commonly whitespace, rather than arbitrary characters located in the middle.
  • Lists provide remove(), but strings do not. Calling remove() on a string results in AttributeError.

How to Choose a Character Removal Method

Method Best for Limitation
replace() Removing one character or substring with simple literal values Several different characters require chained calls or a loop
translate() / maketrans() Deleting many distinct characters at the same time Can be less readable when rules become complex
re.sub() Removing digits, punctuation groups, or values matched by regular expressions Usually slower than replace() for one literal value
Slicing Deleting the first, last, or a position-based character Not suitable for removing every occurrence of a character throughout a string
strip() / lstrip() / rstrip() Removing unwanted leading or trailing characters such as spaces or \n Characters in the middle of the string are not affected

Remove Characters with replace()

str.replace() creates a copy of a string in which every occurrence of the first argument is replaced with the second argument. Supplying an empty string as the replacement deletes the matching value.

Start with a sample string:

Remove every a:

Output:

Both a characters have been removed, while the original s value is still 'abc12321cba'.

Remove Newline Characters

s = 'ab\ncd\nef'
print(s.replace('\n', ''))

Output:

Remove a Substring

print('Helloabc'.replace('Hello', ''))

Output:

Limit the Number of Replacements

The optional third argument limits how many replacements are performed:

print('abababab'.replace('a', 'A', 2))

Output:

Only the first two a characters are changed. See Python String replace() for additional details.

Remove Characters with translate()

str.translate() processes every character through a translation table. Map characters that should be removed to None, or use str.maketrans with a deletion set.

Remove every b:

s = 'abc12321cba'
print(s.translate({ord('b'): None}))

Output:

Remove several characters with one call:

print(s.translate({ord(i): None for i in 'abc'}))

Output:

The same technique can remove newline characters:

print('ab\ncd\nef'.translate({ord('\n'): None}))

Output:

str.maketrans('', '', ',!') creates a deletion-only translation table and can be easier to understand than a dictionary comprehension:

string = "Hello, World!"
print(string.translate(str.maketrans("", "", ",!")))
# Hello World

Remove Characters with Regular Expressions

re.sub() is appropriate when the removal rule uses a pattern rather than a fixed literal. Import re before using it.

Remove digits:

import re

text = "Hello123 World456"
print(re.sub(r'\d+', '', text))
# Hello World

Remove characters that are not alphanumeric:

print(re.sub(r'[^a-zA-Z0-9]', '', "Hello, World! 123"))
# HelloWorld123

Remove non-ASCII characters:

raw = 'Café résumé'
print(re.sub(r'[^\x00-\x7F]+', '', raw))
# Caf rsum

For a more focused explanation of pattern syntax, see Python Regular Expressions.

Remove Characters with Slicing and Comprehensions

Slicing removes characters based on their position without searching through the entire 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 a generator used inside join, can filter individual characters:

vowels = 'aeiouAEIOU'
print(''.join(c for c in 'hello world' if c not in vowels))
# hll wrld

Performance on Large Strings

In a local Python 3.12 test using a string containing one million characters, the approximate results were:

Task Fastest approach
Remove one repeatedly occurring character replace()
Remove several different characters translate() or one re.sub('[abc]', '')
Pattern-based cleanup re.sub()

Running several chained replace() operations on very large strings requires more work than using one translate() call or a single regular expression. For normal application strings, all of these approaches are generally fast enough, so profiling is mainly useful when processing megabytes of text for each request.

Remove Unwanted Characters in Pandas Columns

In data-processing workflows, string methods can be applied to individual columns.

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 filtering 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)

Frequently Asked Questions

1. How Do You Remove a Character from a String in Python?

Use replace() with an empty replacement value:

text = "Hello, World!"
print(text.replace(",", ""))
# Hello World!

When several different characters must be deleted, translate() or re.sub() is preferable to chaining many replace() calls.

2. Is There a remove() Method for Python Strings?

No. list.remove() deletes an element from a list, but strings do not provide a remove() method. Calling "abc".remove("a") produces AttributeError. For strings, use replace(), translate(), re.sub(), or slicing.

3. How Do You Delete a Character from a String by Index?

Use slicing to leave out the index that should be removed:

s = "EXAMPLE"
i = 2  # remove 'A' at index 2
print(s[:i] + s[i+1:])
# EXMPLE

To delete every occurrence of a character regardless of where it appears, use replace() or translate() instead of index-based slicing.

4. What Is strip() in Python and When Should You Use It?

strip() removes characters from the beginning and end of a string, with whitespace used by default. lstrip() and rstrip() perform the same type of trimming on only one side. These methods do not remove characters located in the middle of a string. Use strip() after reading lines from a file. Use replace('\n', '') or translate() when newline characters can occur anywhere in the text. Compare this behavior with Trimming a String in Python.

5. How Do You Remove Multiple Characters from a String in Python?

Option 1 — translate() in one pass:

s = "a1b2c3"
print(s.translate(str.maketrans("", "", "abc")))
# 123

Option 2 — re.sub() with a pattern:

import re
print(re.sub(r'[abc]', '', s))
# 123

Option 3 — loop with replace() for a short and readable list:

for ch in "abc":
    s = s.replace(ch, "")

A loop works well for two or three characters. For larger deletion sets, translate() or a regular expression is generally clearer and performs better with large inputs.

Conclusion

Characters can be removed from Python strings with replace() for literal values, translate() for multiple characters, re.sub() for patterns, and slicing for position-based changes. Choose the method that matches the removal rule, remember that strings are immutable, and return the newly created value to the caller.

Continue with Python string functions, converting a string to a list, and removing spaces from a string.

Deploy Python applications from GitHub with a managed application platform and continue building with a managed generative AI platform when a project requires managed inference.

Continue learning while exploring available options for compute, storage, networking, and managed databases.

Source: digitalocean.com

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: