Here is a short example that should do the trick with regular expressions:

import re

rep = {"condition1": "", "condition2": "text"} # define desired replacements here

# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.items()) 
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)

For example:

>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")
'() and --text--'
Answer from Andrew Clark on Stack Overflow
Top answer
1 of 16
385

Here is a short example that should do the trick with regular expressions:

import re

rep = {"condition1": "", "condition2": "text"} # define desired replacements here

# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.items()) 
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)

For example:

>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")
'() and --text--'
2 of 16
199

You could just make a nice little looping function.

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

where text is the complete string and dic is a dictionary — each definition is a string that will replace a match to the term.

Note: in Python 3, iteritems() has been replaced with items()


Careful: Python dictionaries don't have a reliable order for iteration. This solution only solves your problem if:

  • order of replacements is irrelevant
  • it's ok for a replacement to change the results of previous replacements

Update: The above statement related to ordering of insertion does not apply to Python versions greater than or equal to 3.6, as standard dicts were changed to use insertion ordering for iteration.

For instance:

d = { "cat": "dog", "dog": "pig"}
my_sentence = "This is my cat and this is my dog."
replace_all(my_sentence, d)
print(my_sentence)

Possible output #1:

"This is my pig and this is my pig."

Possible output #2

"This is my dog and this is my pig."

One possible fix is to use an OrderedDict.

from collections import OrderedDict
def replace_all(text, dic):
    for i, j in dic.items():
        text = text.replace(i, j)
    return text
od = OrderedDict([("cat", "dog"), ("dog", "pig")])
my_sentence = "This is my cat and this is my dog."
replace_all(my_sentence, od)
print(my_sentence)

Output:

"This is my pig and this is my pig."

Careful #2: Inefficient if your text string is too big or there are many pairs in the dictionary.

🌐
Python.org
discuss.python.org › python help
Is there an easier way to replace multiple different things at once - Python Help - Discussions on Python.org
March 14, 2022 - im trying to use the .replace() mutiple times at once and i was wondering if there was a cleaner way to do it Code example: with open("user_data.txt", "w") as f: f.write(str(user_data).replace("{","{\n").replace("}","\n}").replace(",",",\n")) f.close() the code works fine but looks a bit messy
Discussions

Which is the better way to include multiple '.replace()' ?
For this case, why not just timestamp = time.strftime("%Y%m%d_%H%M%S", t_obj) More on reddit.com
🌐 r/learnpython
6
3
January 1, 2023
Feature Proposal: Multi-String Replacement Using a Dictionary in the .replace() Method - Ideas - Discussions on Python.org
Summary: I would like to propose an extension to the .replace() method to allow multiple substring replacements in a string using a dictionary. Currently, .replace() accepts only two arguments (the value to be replaced and the replacement value), which results in the need for multiple calls ... More on discuss.python.org
🌐 discuss.python.org
13
October 21, 2024
Vectorized .str.replace() for multiple characters in pandas
I think my count and year columns are breaking because of the if statement excluding those two columns. More on reddit.com
🌐 r/learnpython
3
1
June 9, 2022
python - Replace multiple substrings in a Pandas series with a value - Stack Overflow
Thanks for sharing, but when I ... and 'str'". What did I do wrong here? 2022-11-18T21:16:28.637Z+00:00 ... Thanks a lot Cam! It works. Apparently it's due to my poor regex knowledge. I suppose \s captures whitespaces. What was wrong with my method tho? 2022-11-21T21:19:24.843Z+00:00 ... def replace_values(series, ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Bobby Hadz
bobbyhadz.com › blog › python-replace-multiple-characters-in-string
How to replace multiple Characters in a String in Python | bobbyhadz
Chaining multiple calls to the str.replace() method is quite efficient, so if you only have to replace a couple of substrings in the string, this approach works perfectly fine. Alternatively, you can store the characters to be replaced and the replacements in a list. Here is an example that uses a list of replacements. Store the characters to be replaced and the replacements in a list. Use a for loop to iterate over the list. Use the str.replace() method to replace each character in the string.
🌐
GeeksforGeeks
geeksforgeeks.org › python-replace-multiple-characters-at-once
Python - Replace multiple characters at once - GeeksforGeeks
January 8, 2025 - Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements.
🌐
Reddit
reddit.com › r/learnpython › which is the better way to include multiple '.replace()' ?
r/learnpython on Reddit: Which is the better way to include multiple '.replace()' ?
January 1, 2023 -

I have a string formatted timestamp that I would like to replace some characters.

Which is the better way to do this (of the two I have thought of!) ?

1 -

timestamp = time.strftime("%Y-%m-%d %H:%M:%S", t_obj).replace("-", "").replace(" ", "_").replace(":", "")

2 -

timestamp  = time.strftime("%Y-%m-%d %H:%M:%S", t_obj)
timestamp  = timestamp .replace("-", "") 
timestamp  = timestamp .replace(" ", "_") 
timestamp  = timestamp .replace(":", "")

First approach reads nicer but wouldn't readability wouldn't scale as well if I wanted to do more replaces.

Second one, is using the same variable name over and over like that until it's in the state you want considered bad practice maybe?

Cheers !

🌐
FavTutor
favtutor.com › blogs › replace-multiple-characters-in-string-python
5 Ways to Replace Multiple Characters in String in Python
October 10, 2022 - The methods discussed so far involve regular expressions and can be used with lists and dictionaries. However, Python offers another method that uses dictionaries to map old values to new values, and hence to replace multiple characters in a string.
🌐
YouTube
youtube.com › python basics
Python Basics Tutorial How to Replace Multiple String Characters || String Replace - YouTube
Learn how to replace more than one character at a time with python programmingPatreon:https://www.patreon.com/Python_basicsGithub:https://github.com/Python-b...
Published: November 30, 2020
Views: 19K
Find elsewhere
🌐
Note.nkmk.me
note.nkmk.me › home › python
Replace Strings in Python: replace(), translate(), and Regex | note.nkmk.me
May 4, 2025 - The translate() method replaces ... documentation · str.maketrans() — Python 3.13.3 documentation · You can pass a dictionary to str.maketrans(), where each key is a single character to be replaced, and the corresponding ...
🌐
Python Guides
pythonguides.com › pandas-str-replace-multiple-values-in-python
Pandas Str.replace Multiple Values In Python [3 Examples]
May 22, 2025 - import pandas as pd # Sample US demographics data data = { 'Gender': ['M', 'F', 'M', 'F', 'M'], 'Education': ['HS', 'BA', 'MA', 'PHD', 'HS'], 'Employment': ['FT', 'PT', 'UN', 'FT', 'PT'] } df = pd.DataFrame(data) print("Original DataFrame:") print(df) # Define replacement dictionaries for each column replacements = { 'Gender': {'M': 'Male', 'F': 'Female'}, 'Education': {'HS': 'High School', 'BA': 'Bachelor', 'MA': 'Master', 'PHD': 'Doctorate'}, 'Employment': {'FT': 'Full-time', 'PT': 'Part-time', 'UN': 'Unemployed'} } # Apply replacements to multiple columns for column, mapping in replacements
🌐
Mimo
mimo.org › glossary › python › string-replace-method
Master Python's String Replace Method for Text Manipulation
You can also use replace() to replace single characters in a string rather than substrings. ... To replace multiple different characters in a string, you can chain multiple replace() calls or use the translate() method with a translation table.
🌐
Python.org
discuss.python.org › ideas
Feature Proposal: Multi-String Replacement Using a Dictionary in the .replace() Method - Ideas - Discussions on Python.org
October 21, 2024 - Summary: I would like to propose an extension to the .replace() method to allow multiple substring replacements in a string using a dictionary. Currently, .replace() accepts only two arguments (the value to be replaced and the replacement value), which results in the need for multiple calls ...
🌐
Reddit
reddit.com › r/learnpython › vectorized .str.replace() for multiple characters in pandas
r/learnpython on Reddit: Vectorized .str.replace() for multiple characters in pandas
June 9, 2022 -

I have a dataframe:

 {'country': {0: 'Afghanistan?*', 1: 'Albania?*'},
 'region': {0: 'Asia', 1: 'Europe'},
 'subregion': {0: 'Southern Asia', 1: 'Southern Europe'},
 'rate_per_1000': {0: 6.7, 1: 2.1},
 'count': {0: '2,474', 1: '61'},
 'year': {0: 2018, 1: 2020},
 'source': {0: 'NSO', 1: 'NSO'}}

          country  region        subregion  rate_per_1000  count  year source
0   Afghanistan?*    Asia    Southern Asia            6.7  2,474  2018    NSO
1       Albania?*  Europe  Southern Europe            2.1     61  2020    NSO

There are multiple bad characters here that I want to get rid of. I made a short function for .apply() to get rid of them, however I am looping over a defined list of bad characters. This gives a bad code smell to me, I think this operation could be more vectorized in some way. This is what I've tried:

bad_chars = ['?', '*', ',']

def string_cleaner(col):
    if col.dtype == 'object':
        for char in bad_chars:
            col = col.str.replace(f'{char}', '')
        return col

homicide_by_country = homicide_by_country.apply(string_cleaner)

homicide_by_country
        country  region        subregion rate_per_1000 count  year source
0   Afghanistan    Asia    Southern Asia          None  2474  None    NSO
1       Albania  Europe  Southern Europe          None    61  None    NSO

My desired outcome is a more pythonic/pandonic technique for accomplishing the same outcome.

You may notice for some reason my rate_per_1000 columns goes blank. I haven't troubleshot that problem yet but if you spot something obvious I'm all ears.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-replace-k-with-multiple-values
Python - Replace K with Multiple values - GeeksforGeeks
March 22, 2024 - Input : test_str = '* is *', repl_char = '*', repl_list = ['Gfg', 'Best'] Output : Gfg is Best ... The combination of above functions can be used to solve this problem. In this, we perform the task of replacing using replace() and increase the index counter after each replacement. ... # Python3 code to demonstrate working of # Replace K with Multiple values # Using loop + replace() # initializing strings test_str = '_ is _ .
🌐
W3Schools
w3schools.com › python › ref_string_replace.asp
Python String replace() Method
Remove List Duplicates Reverse ... Study Plan Python Interview Q&A Python Training ... The replace() method replaces a specified phrase with another specified phrase....
🌐
michael harty
mharty3.github.io › til › python › string-translate
Replace multiple characters in a string using string.translate() (python) - michael harty
October 30, 2023 - If you need to replace a character in a string, you can use string.replace(old, new) or re.swap(pattern, new, string) if you need regex.
Top answer
1 of 6
44

You can perform this task by forming a |-separated string. This works because pd.Series.str.replace accepts regex:

Replace occurrences of pattern/regex in the Series/Index with some other string. Equivalent to str.replace() or re.sub().

This avoids the need to create a dictionary.

import pandas as pd

df = pd.DataFrame({'A': ['LOCAL TEST', 'TEST FOREIGN', 'ANOTHER HELLO', 'NOTHING']})

pattern = '|'.join(['LOCAL', 'FOREIGN', 'HELLO'])

df['A'] = df['A'].str.replace(pattern, 'CORP', regex=True)

#               A
# 0     CORP TEST
# 1     TEST CORP
# 2  ANOTHER CORP
# 3       NOTHING
2 of 6
17

The answer of @Rakesh is very neat but does not allow for substrings. With a small change however, it does.

  1. Use a replacement dictionary because it makes it much more generic
  2. Add the keyword argument regex=True to Series.replace() (not Series.str.replace) This does two things actually: It changes your replacement to regex replacement, which is much more powerful but you will have to escape special characters. Beware for that. Secondly it will make the replace work on substrings instead of the entire string. Which is really cool!
replacement = {
    "LOCAL": "CORP",
    "FOREIGN": "CORP",
    "HELLO": "CORP"
}

dataUS['sec_type'].replace(replacement, regex=True)

Full code example

dataUS = pd.DataFrame({'sec_type': ['LOCAL', 'Sample text LOCAL', 'Sample text LOCAL sample FOREIGN']})

replacement = {
    "LOCAL": "CORP",
    "FOREIGN": "CORP",
    "HELLO": "CORP"
}

dataUS['sec_type'].replace(replacement, regex=True)

Output

0                            CORP
1                            CORP
2                Sample text CORP
3    Sample text CORP sample CORP
Name: sec_type, dtype: object
🌐
Reddit
reddit.com › r/learnpython › .replace() for multiple conditions?
r/learnpython on Reddit: .replace() for multiple conditions?
November 14, 2022 -

so i used .replace() to remove a certain character from a filename

but now i want to do it for more characters.

how is this done in python?

this is what i tried:

char_remove = ['?', '"', '!']
for char in char_remove:
    movie_title = (str(submission.title) + '.mp4').replace(char_remove, '')

but i got

TypeError: replace() argument 1 must be str, not list
🌐
HCL GUVI
studytonight.com › python-howtos › how-to-replace-multiple-substrings-of-a-string-in-python
HCL GUVI | Learn to code in your native language
With IITM Pravartak affiliations, master Full-Stack, Data Science, DevOps, UI/UX, and more in multiple languages!Explore More · Looking for flexibility? HCL GUVI's 200+ self-paced courses let you learn anytime, anywhere! From free lessons to IIT-M & Autodesk-certified programs, gain in-demand skills in your preferred language.Explore More · Enhance your coding skills with HCL GUVI's Practice Platforms—interactive, structured, and designed to help you master programming effortlessly.