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.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-replace-multiple-characters-at-once
Python - Replace multiple characters at once - GeeksforGeeks
July 12, 2025 - Using a loop allows all specified characters to be replaced sequentially. While effective, this method may be slower due to repeated operations on the string. Regular expressions provide a flexible way to replace multiple characters.
Discussions

Is there an easier way to replace multiple different things at once
On a high level, the method you’ve demonstrated is both idiomatic and the fastest (or one at least one of them). However, a bit of reorganization will make it both a little more efficient (by not leaving the file handle open as long), and will ensure it looks cleaner and more readable. More on discuss.python.org
🌐 discuss.python.org
4
1
March 14, 2022
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
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
how to replace multiple characters in one go with the .replace() function?
re.sub, maketrans, or a list comprehension with join newstr = ''.join('*' if c in 'aA' else c for c in oldstr) More on reddit.com
🌐 r/learnpython
5
1
October 7, 2020
🌐
Note.nkmk.me
note.nkmk.me › home › python
Replace Strings in Python: replace(), translate(), and Regex | note.nkmk.me
May 4, 2025 - To replace the content in a text file, read the file into a string, process it, and save the result back to the file. Read, write, and create files in Python (with and open()) The replace() method replaces all occurrences of a substring with another.
🌐
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
🌐
FavTutor
favtutor.com › blogs › replace-multiple-characters-in-string-python
5 Ways to Replace Multiple Characters in String in Python
October 10, 2022 - After initializing the list, you can either replace the mentioned characters with the same character (i.e. all by one) or with multiple characters (i.e. a different character for each). Case: Replacing multiple characters with the same character: # multiple characters to be replace string = "FavTutor Blog: How to Remove multiple characters in a string in Python" # let's say we need to replace characters - 't', 'l', 'r' # creating a list for the characters to be replaced char_remov = ["t", "l", "r"] print("Original string: " + string) # let's say we need to replace them with a special character '#' # Using the for loop for each character of char_remov for char in char_remov: # replace() "returns" an altered string string = string.replace(char, "#") print("Altered string: " + string)
🌐
thisPointer
thispointer.com › home › python › python: replace multiple characters in a string
Python: Replace multiple characters in a string - thisPointer
April 30, 2023 - Replace multiple characters in a string using the replace() Replace multiple characters in a string using the translate () Replace multiple characters in a string using regex · Replace multiple characters in a string using for loop ...
🌐
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
🌐
Mimo
mimo.org › glossary › python › string-replace-method
Master Python's String Replace Method for Text Manipulation
Learn basics, data types, control flow, and more ... The replace() method returns a copy of the string after replacing the substrings without changing the original string. ... count: An optional parameter that specifies the number of occurrences to replace. The default value (-1) replaces all ...
🌐
Delft Stack
delftstack.com › home › howto › python › python replace multiple characters
How to Replace Multiple Characters in a String in Python | Delft Stack
February 2, 2024 - The modified string is assigned back to input_string within the loop, allowing multiple replacements to be performed sequentially. Finally, the modified string is returned from the function. We demonstrate the function by defining an original_string and a replacement_dict. In this case, we want to replace H with h, o with 0, l with 1, and d with !. The result of the function call is printed, showing the string after the specified replacements. ... In Python, you can import the re module, which has an amount of expression matching operations for regex for you to utilize.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-replace-all-occurrences-of-a-substring-in-a-string
Python - Replace all Occurrences of a Substring in a String - GeeksforGeeks
August 13, 2026 - Explanation: re.sub(pattern, replacement, string) finds all occurrences of pattern and replaces them with replacement. This method splits the string at each occurrence of the target and joins it back with the replacement.
🌐
GeeksforGeeks
geeksforgeeks.org › python-replace-multiple-words-with-k
Replace multiple words with K - Python - GeeksforGeeks
January 18, 2025 - In this method we use for loop to iterate through each word in the list li and then use the replace() method to replace all occurrences of that word in the string s with the replacement word K.
🌐
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), ...
🌐
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 !

🌐
GitHub
gist.github.com › carlsmith › b2e6ba538ca6f58689b4c18f46fef11c
A Python function that does multiple string replace ops in a single pass. · GitHub
string = "spam foo bar foo bar spam" substitutions = {"foo": "FOO", "bar": "BAR"} output = replace(string, substitutions) ... Thanks! Nice Solution!!!! ... One of the best Method hats off to you ! ... Hi all! I am a newly in programming Python, and found your code regarding easy replacing text, using Python.
🌐
O'Reilly
oreilly.com › library › view › python-cookbook › 0596001673 › ch03s15.html
Replacing Multiple Patterns in a Single Pass - Python Cookbook [Book]
July 19, 2002 - Here is how you can produce a result string from an input string where each occurrence of any key in a given dictionary is replaced by the corresponding value in the dictionary: # requires Python 2.1 or later from _ _future_ _ import nested_scopes import re # the simplest, lambda-based implementation def multiple_replace(adict, text): # Create a regular expression from all of the dictionary keys regex = re.compile("|".join(map(re.escape, adict.keys( )))) # For each match, look up the corresponding value in the dictionary return regex.sub(lambda match: adict[match.group(0)], text)
Authors: Alex MartelliDavid Ascher
Published: 2002
Pages: 608
🌐
Tutorialspoint
tutorialspoint.com › python › string_replace.htm
Python String replace() Method
The Python String replace() method replaces all occurrences of one substring in a string with another substring. This method is used to create another string by replacing some parts of the original string, whose gist might remain unmodified.
🌐
Reddit
reddit.com › r/learnpython › how to replace multiple characters in one go with the .replace() function?
r/learnpython on Reddit: how to replace multiple characters in one go with the .replace() function?
October 7, 2020 -

Hello, I would like to replace a certain letter in a string with a '*' (don't ask lol)

The problem is it will only either do it for the lower case letters or upper case letters.

Is there a way to get the function to replace both upper and lower case letters or am I going to need to use the function twice?

Thanks

🌐
GitHub
github.com › python › cpython › issues › 100561
Add support to replace multiple strings at once · Issue #100561 · python/cpython
December 27, 2022 - s = "The quick brown fox jumps over the lazy dog" s = s.replace(("brown", "red"), ("lazy", "quick")) It would work the same for example like str.startswith() where I can put tuple of strings.
Author: python
🌐
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
Hone your bug-fixing skills with real-world debugging challenges in Python, C++, JavaScript, and Golang. More languages coming soon!Try Now > ... A free online compiler supporting 20+ programming languages with auto-complete, debugging, and AI-powered code generation—all in the cloud!Try Now >