How to Replace Multiple Characters in a String in Python
This tutorial showed you how to replace multiple characters in a string in Python.
Suppose we want to remove special characters from a string and replace them with spaces.
-
The list of special characters to remove is
!#$%^&*()
. -
Additionally, we want to replace commas with whitespace
,
. - The sample text we will manipulate.
A!!!,Quick,brown#$,fox,ju%m%^ped,ov&er&),th(e*,lazy,d#!og$$$
str.replace()
Replace multiple characters in Python using
We can use str
the replace()
method of to replace a substring with a different output.
replace()
It accepts two parameters, the first one is the regex pattern you want to match the string against, and the second one is the replacement string for the matched string.
It replace()
also has an optional third parameter in that accepts an integer that sets the maximum count
number of replacements to be performed. If you pass 2
as count
the parameter, replace()
the function will only match and replace 2 instances in the string.
str.replace('Hello', 'Hi')
will Hi
replace all instances of in a string with Hello
. If you have a string Hello World
and run the replace function on it, it will become Hi World
.
Let's use it on the sample text declared above replace
. First we remove the special characters by looping over each character and replacing it with an empty string, and then we convert the commas to spaces.
txt = "A!!!,Quick,brown#$,fox,ju%m%^ped,ov&er&),th(e*,lazy,d#!og$$$"
def processString(txt):
specialChars = "!#$%^&*()"
for specialChar in specialChars:
txt = txt.replace(specialChar, "")
print(txt) # A,Quick,brown,fox,jumped,over,the,lazy,dog
txt = txt.replace(",", " ")
print(txt) # A Quick brown fox jumped over the lazy dog
This means that spChars
any characters within the square brackets will be replaced by an empty string, using txt.replace(spChars, '')
.
The string result of the first replace()
function will be:
A, Quick, brown, fox, jumped, over, the, lazy, dog
The next call will replace replace()
all instances of commas with single spaces.,
A Quick brown fox jumped over the lazy dog
Use re.sub()
or re.subn()
to replace multiple characters in Python
In Python, you can import re
the module, which has a large number of regex expression matching operations for you to use.
re
Two such functions in are sub()
and subn()
.
Let's declare another string example for these methods. Suppose we want to replace all the numbers in a string with X.
txt = "Hi, my phone number is 089992654231. I am 34 years old. I live in 221B Baker Street. I have 1,000,000 in my bank account."
re.sub()
Replacing multiple characters in Python using
This function has 3 main parameters. The first parameter accepts a regex pattern, the second parameter is a string to replace the matched pattern with, and the third parameter is the string to operate on.
Create a function that converts all the numbers in a string to X.
import re
txt = "Hi, my phone number is 089992654231. I am 34 years old. I live in 221B Baker Street. I have 1,000,000 in my bank account."
def processString3(txt):
txt = re.sub("[0-9]", "X", txt)
print(txt)
processString3(txt)
Output:
Hi, my phone number is XXXXXXXXXXXX. I am XX years old. I live in XXXB Baker Street. I have X,XXX,XXX in my bank account.
re.subn()
Replacing multiple characters in Python
This function is essentially re.sub()
the same as , but returns a tuple of the transformed string and the number of replacements.
import re
txt = "Hi, my phone number is 089992654231. I am 34 years old. I live in 221B Baker Street. I have 1,000,000 in my bank account."
def processString4(txt):
txt, n = re.subn("[0-9]", "X", txt)
print(txt)
processString4(txt)
Output:
Hi, my phone number is XXXXXXXXXXXX. I am XX years old. I live in XXXB Baker Street. I have X,XXX,XXX in my bank account.'
txt, n = re.subn("[0-9]", "X", txt)
In the above code snippet, the processed string is assigned to txt
and the replacement counter is assigned to n
.
re.subn()
Useful if you want to make note of how many pattern groups there are as an indicator or for further processing .
Replacing multiple characters using translate()
and in Pythonmaketrans()
translate()
and maketrans()
use a different approach than regex in that they utilize a dictionary to map old values to new values.
maketrans()
Accepts 3 arguments or a mapping of dictionaries.
-
str1
- The string to replace. -
str2
- Replacement string for the above characters. -
str3
- The string to be deleted.
maketrans()
A mapping between original strings and their replacements.
translate()
Accepts whatever maketrans()
is returned, and then generates the translated string.
Let's say we want to convert all lowercase vowels in a string to uppercase and remove all x, y, and z in the string.
txt = "Hi, my name is Mary. I like zebras and xylophones."
def processString5(txt):
transTable = txt.maketrans("aeiou", "AEIOU", "xyz")
txt = txt.translate(transTable)
print(txt)
processString5(txt)
Output:
HI, m nAmE Is MAr. I lIkE EbrAs And lOphOnEs.
translate()
Convert all lowercase vowels to uppercase and remove all instances of x, y, and z.
Another way to use these methods is to use a single mapping dictionary instead of three parameters.
def processString6(txt):
dictionary = {
"a": "A",
"e": "E",
"i": "I",
"o": "O",
"u": "U",
"x": None,
"y": None,
"z": None,
}
transTable = txt.maketrans(dictionary)
txt = txt.translate(transTable)
print(txt)
This will still produce processString5
the same output as , but is implemented using a dictionary. You can use whichever method is more convenient for you.
In summary, there are various ways to replace multiple characters in a string by using built-in functions in Python or functions from imported libraries.
The most common approach is to use replace()
. re.sub()
and subn()
is also fairly easy to use and learn. translate()
uses a different approach as it does not rely on regular expressions to perform string manipulation, but rather on dictionaries and Maps.
If you wanted, you could even manually loop over the string using a for loop and add your own conditions to replace, just using substring()
or split()
, but this would be very inefficient and redundant. Python provides existing functions to do this for you, which is much easier than doing the tedious work yourself.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
How to convert an integer to bytes
Publish Date:2025/05/08 Views:77 Category:Python
-
Converting an integer int to a byte bytes is the inverse of bytes converting a byte to an integer . Most of the to methods int described in this article are the inverse of the to methods. int bytes bytes int Generic method for converting in
How to remove the last character from a string in Python
Publish Date:2025/05/08 Views:141 Category:Python
-
A Python string is a combination of characters enclosed in double or single quotes. Python provides multiple functions to manipulate strings. This article will show you different ways to remove the last character and specific characters fro
How to Remove a Substring from a String in Python
Publish Date:2025/05/08 Views:182 Category:Python
-
This tutorial explains how to delete a substring in a string in Python. It will show you that strings cannot just be deleted, but only replaced. This tutorial also lists some sample codes to clarify the concepts, as the method has changed c
Get parent directory in Python
Publish Date:2025/05/08 Views:109 Category:Python
-
This tutorial will explain various ways to get the parent directory of a path in Python. A parent directory is a directory above or above a given directory or file. For example, C:\folder\subfolder\myfile.txt the parent directory of the pat
Catching keyboard interrupt errors in Python
Publish Date:2025/05/08 Views:106 Category:Python
-
The error occurs when a user manually tries to stop a running program using Ctrl + C or Ctrl + , or in the case of Jupyter Notebook by interrupting the kernel . To prevent accidental use of , which often occurs , we can use exception handli
Implementing a Low-Pass Filter in Python
Publish Date:2025/05/07 Views:90 Category:Python
-
Low pass filter is a term in signal processing basics and is often used to filter signals to obtain more accurate results. This tutorial will discuss the low-pass filter and how to create and implement it in Python. A low-pass filter is use
Implementing Curl command in Python using requests module
Publish Date:2025/05/07 Views:98 Category:Python
-
requests This article will discuss and implement different curl commands using the module in Python . requests Installing modules in Python Python provides us with requests the module to execute curl command. Install it in Python 3 using Pi
Using fetchall() in Python to extract elements from a database
Publish Date:2025/05/07 Views:173 Category:Python
-
This article aims to describe fetchall() the working methods of extracting elements from a database using and how to display them correctly. This article will also discuss list(cursor) how functions can be used in programs. fetchall() Extra
Parsing log files in Python
Publish Date:2025/05/07 Views:106 Category:Python
-
Log files contain information about events that occurred during the operation of a software system or application. These events include errors, requests made by users, bugs, etc. Developers can further scan these usage details to find poten