
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to remove specific characters from a string in Python?
The string class has a method replace that can be used to replace substrings in a string. We can use this method to replace characters we want to remove with an empty string. For example:
>>> "Hello people".replace("e", "") "Hllo popl"
If you want to remove multiple characters from a string in a single line, it's better to use regular expressions. You can separate multiple characters by "|" and use the re.sub(chars_to_replace, string_to_replace_with, str). For example:
import re print (re.sub("e|l", " ", "Hello people"))
OUTPUT
H o p op
Note: You can also use the [ ] to create group of characters to replace in regex.
- Related Articles
- How to remove characters except digits from string in Python?
- How to Remove Characters from a String in Arduino?
- Program to remove duplicate characters from a given string in Python
- How to scan a string for specific characters in Python?
- How to remove certain characters from a string in C++?
- How to remove all special characters, punctuation and spaces from a string in Python?
- How to remove a list of characters in string in Python?
- How to remove all non-alphanumeric characters from a string in MySQL?
- Remove characters from a string contained in another string with JavaScript?
- How to Remove Punctuations From a String in Python?
- C# Program to remove duplicate characters from String
- JavaScript Remove non-duplicate characters from string
- JavaScript - Remove first n characters from string
- PHP program to remove non-alphanumeric characters from string
- How to print characters from a string starting from 3rd to 5th in Python?

Advertisements