惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Announcements
Recent Announcements
J
Java Code Geeks
U
Unit 42
GbyAI
GbyAI
大猫的无限游戏
大猫的无限游戏
L
LangChain Blog
D
Docker
F
Fortinet All Blogs
N
Netflix TechBlog - Medium
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
罗磊的独立博客
I
InfoQ
The Cloudflare Blog
小众软件
小众软件
V
Visual Studio Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
S
SegmentFault 最新的问题
爱范儿
爱范儿
Hugging Face - Blog
Hugging Face - Blog
P
Proofpoint News Feed
V
V2EX
月光博客
月光博客
Martin Fowler
Martin Fowler

DigitalOcean Community Tutorials

It's Time to Break Up with Your Cloud: Why AI Teams are Switching We Built a Private-Document AI App to Test Platform Security. Here Is What We Could Actually Verify. PostgreSQL Explained: A Complete Beginner-to-Advanced Guide How To Install and Configure Postfix on Ubuntu How To Build a Web Application Using Flask in Python 3 Build AI Reading List with DigitalOcean Functions and Mistral How To Concatenate Strings in Python How to Allow MySQL Remote Access Securely How To Install and Use Docker on Rocky Linux How To Build a Multi-Agent AI System with Docker Agent DSPy Use Cases: Build Optimized LLM Pipelines How To Submit AJAX Forms with jQuery Build an AI-Powered GPU Fleet Optimizer with the DigitalOcean AI Platform ADK Monitor GPU Utilization in Real Time: A Complete Guide Reduce File Size of Images in Linux - CLI and GUI methods Reduce PDF File Size in Linux: Tools and Methods How To Set Up a Private Docker Registry on Ubuntu How To Troubleshoot Terraform: Errors and Fixes How to Use Go Modules Python Multiprocessing Example: Process, Pool & Queue Convert Class Components to Functional Components with React Hooks How To Install and Configure Ansible on Ubuntu LLM Tokenizers Simplified: BPE, SentencePiece, and More How To Monitor System Authentication Logs on Ubuntu How to Use Traceroute and MTR to Diagnose Network Issues How to Deploy Postgres to Kubernetes Cluster Importing Packages in Go: A Complete Guide Create RAID Arrays with mdadm on Ubuntu How To Make an HTTP Server in Go How To Set Up Time Synchronization on Ubuntu
How to Remove Characters from a String in Python
Anish Singh Walia · 2022-08-04 · via DigitalOcean Community Tutorials

Introduction

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.

Key takeaways

  • Python strings are immutable: every removal returns a new string; the original is unchanged.
  • Use replace(old, '') for one character or substring; pass a third argument to limit how many replacements run.
  • Use translate() with str.maketrans('', '', chars) or a mapping dict to remove several characters in a single pass.
  • Use re.sub() when removal depends on a pattern (digits, punctuation, non-ASCII).
  • Use slicing (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.
  • Lists have remove(); strings do not—calling remove() on a string raises AttributeError.

How to choose a removal method

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

Remove characters with 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:

  1. s = 'abc12321cba'

Remove every a:

  1. print(s.replace('a', ''))

Output:

Output

bc12321cb

Both a characters are gone; the original s is still 'abc12321cba'.

Remove newline characters

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

Output:

Output

abcdef

Remove a substring

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

Output:

Output

abc

Limit how many replacements run

The optional third argument caps replacements:

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

Output:

Output

AbAbabab

Only the first two a characters change. See Python String replace() for more detail.

Remove characters with 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:

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

Output:

Output

ac12321ca

Remove several characters in one call:

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

Output:

Output

12321

The same idiom works for newlines:

  1. 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

Remove characters with regular expressions

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.

Remove characters with slicing and comprehensions

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

Performance on large strings

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.

Remove unwanted characters in Pandas columns

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.

FAQs

1. How do you remove a character from a string in Python?

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.

2. Is there a 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.

3. How do I delete a character from a string by index?

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.

4. What is 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.

5. How do I remove multiple characters from 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.

Conclusion

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.

Still looking for an answer?

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.