How to Remove Characters from a String in Python

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

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

Deploy Python applications directly 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 value remains unchanged.
  • Use replace(old, '') to remove one character or substring. A third argument can limit the number of replacements.
  • Use translate() together with str.maketrans('', '', chars) or a mapping dictionary to remove multiple characters in one pass.
  • Use re.sub() when characters must be removed according to a pattern, such as digits, punctuation, or non-ASCII characters.
  • Use slicing, such as s[1:], s[:-1], or s[:i] + s[i+1:], to remove the first, last, or indexed character without scanning the complete string.
  • strip(), lstrip(), and rstrip() remove characters from the beginning or end of a string, commonly whitespace, rather than removing arbitrary characters from the middle.
  • Lists provide remove(), but strings do not. Calling remove() on a string results in an AttributeError.

How to Choose a String Character Removal Method

Method Best for Limitation
replace() One character or substring; straightforward literal values Removing several different characters requires chained calls or a loop
translate() / maketrans() Removing many different characters at the same time Can be harder to read when rules become complex
re.sub() Digits, punctuation groups, and regular-expression rules Usually slower than replace() for one fixed literal
Slicing Removing the first, last, or a position-based character Not intended 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 located in the middle are not affected

Remove Characters from a Python String with replace()

str.replace() creates a copy of a string in which every occurrence of the first argument is replaced with the second argument. To delete matching text, provide an empty string as the replacement.

Create an example string:

Remove every a:

Output:

Both a characters have been removed, while the original value of s remains '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 parameter sets the maximum number of replacements:

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

Output:

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

Remove Characters from a Python String with translate()

str.translate() processes characters through a translation table. Assign unwanted characters to None, or create a deletion table with str.maketrans(), to remove them.

Remove every b:

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

Output:

Delete several characters with a single call:

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

Output:

The same approach 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 from a Python String with Regular Expressions

re.sub() is suitable when the removal rule is defined by a pattern rather than a fixed character or substring. 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 letters or numbers:

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

Remove Characters with Python Slicing and Comprehensions

Slicing removes characters according to 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 expression passed to join(), can filter individual characters:

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

Performance When Removing Characters from Large Python Strings

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

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

Applying several chained replace() operations to very large strings requires more work than one translate() call or a single regular expression. For ordinary application strings, all of these approaches are generally fast enough. Profiling becomes important when processing megabytes of text for each request.

Remove Unwanted Characters from Pandas Columns

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

Keep only digits by using .str.replace() together with 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)

Create a 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)

Frequently Asked Questions

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

Call replace() and use an empty string as the replacement:

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

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

2. Does Python Provide a remove() Method for Strings?

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

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

Use slicing to omit the position that should be removed:

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

If every occurrence of a character must be removed regardless of its position, use replace() or translate() rather than 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 from the middle of a string. Use strip() after reading lines from a file. Use replace('\n', '') or translate() when newline characters can appear anywhere in the text. Compare this approach with Trimming a String in Python.

5. How Can 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 groups of characters, translate() or a regular expression is usually easier to understand and performs better with large inputs.

Conclusion

Characters can be removed from Python strings with replace() for fixed literals, translate() for groups of characters, re.sub() for pattern-based rules, and slicing for position-based changes. Choose the method that fits the removal rule, remember that Python 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 with a managed generative AI platform when a project requires managed inference.

Source: digitalocean.com

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: