As in 2.x, use str.replace().

Example:

>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'
Answer from Ignacio Vazquez-Abrams on Stack Overflow
🌐
W3Schools
w3schools.com › python › ref_string_replace.asp
Python String replace() Method
Remove List Duplicates Reverse ... Python Interview Q&A Python Training ... The replace() method replaces a specified phrase with another specified phrase....
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.Series.str.replace.html
pandas.Series.str.replace — pandas 3.0.5 documentation
Method to replace occurrences of a substring with another substring. ... Extract substrings using a regular expression. ... Find all occurrences of a pattern or regex in each string.
Discussions

Str.replace of a set of characters - Ideas - Discussions on Python.org
I would like str.replace, when given a set of characters, to replace occurrence of any of the characters in the set. I.e. 'ASDFGH'.replace(set('SFH'), '') == 'ADG' should then hold. It would mean I would not have to go to the trouble of using the re module for a common string operation. More on discuss.python.org
🌐 discuss.python.org
0
December 1, 2019
Making str.replace() accept lists - Ideas - Discussions on Python.org
Syntax of the method: str.replace(old, new, count=-1) What if replace could accept two lists instead of two strings. Often I find in code: text.replace(a, b).replace(c, d) The concatenation of replace calls can cause a unnecessary performance hit if the string is large or the call is the calls ... More on discuss.python.org
🌐 discuss.python.org
3
May 9, 2020
Python: How can I replace one specific character on a string while leaving the rest of the string as it was?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
12
6
October 18, 2023
python - How to replace multiple substrings of a string? - Stack Overflow
Note: As with all recursive functions in python, too large recursion depth (i.e. too large replacement dictionaries) will result in an error. See e.g. here. ... @Pablo Interesting. How large? Note that this happens for all recursive functions. See for example here: stackoverflow.com/questions/3323001/… 2019-11-27T07:30:57.897Z+00:00 ... My dictionary of substitutions is close to 100k terms... so far using string... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Mimo
mimo.org › glossary › python › string-replace-method
Master Python's String Replace Method for Text Manipulation
replace() is a string method that replaces a string’s occurrences of a substring with another substring. The replace() method takes the old substring, the new substring, and an optional count parameter. When present, count specifies the number of occurrences to replace.
🌐
Python.org
discuss.python.org › ideas
Str.replace of a set of characters - Ideas - Discussions on Python.org
December 1, 2019 - I would like str.replace, when given a set of characters, to replace occurrence of any of the characters in the set. I.e. 'ASDFGH'.replace(set('SFH'), '') == 'ADG' should then hold. It would mean I would not have to go …
🌐
Python.org
discuss.python.org › ideas
Making str.replace() accept lists - Ideas - Discussions on Python.org
May 9, 2020 - Syntax of the method: str.replace(old, new, count=-1) What if replace could accept two lists instead of two strings. Often I find in code: text.replace(a, b).replace(c, d) The concatenation of replace calls can cause…
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-string-replace
Python String replace() Method - GeeksforGeeks
July 7, 2026 - A new string is returned with the updated values, original string s remains unchanged. ... count (optional): Specifies the maximum number of replacements to perform.
🌐
Server Academy
serveracademy.com › blog › python-replace-function
Python Replace() Function Blog | Server Academy
July 23, 2026 - The method in Python is a powerful tool for working with strings, allowing you to replace parts of a string with new values. Whether you’re changing characters…
🌐
StrataScratch
stratascratch.com › blog › how-to-replace-a-character-in-a-python-string
How to Replace a Character in a Python String - StrataScratch
October 18, 2024 - For more complex replacement scenarios, Python regular expressions can be useful. These are sequences of characters that form a search pattern for matching text. We already used them in str.replace(), but when talking about using regular expressions for character replacement, I mean using the re.sub() function.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Replace Strings in Python: replace(), translate(), and Regex
May 4, 2025 - In regular strings ('' or ""), use double backslashes (\\1) to reference a group. In raw strings (r'' or r""), a single backslash (\1) works. ... To perform more complex replacements, provide a function that receives a match object and returns ...
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 documentation
docs.python.org › 3 › library › stdtypes.html
Built-in Types — Python 3.14.7 documentation
Return a copy of the string with all occurrences of substring old replaced by new. If count is given, only the first count occurrences are replaced. If count is not specified or -1, then all occurrences are replaced.
🌐
Quora
quora.com › In-Python-how-do-I-use-the-replace-function-on-strings-to-replace-multiple-characters-e-g-a-space-or-any-special-character-with-the-empty-string-E-g-Tes-ting-replace-only-replaces-the-space-not-the
In Python, how do I use the .replace() function on strings to replace multiple characters, e.g. a space or any special character, with th...
Answer (1 of 4): Why do you ask how to use a function (method) to do something after you’ve already demonstrated to yourself that the function/method doesn’t do that? Perhaps it’s better to describe what you want to accomplish and ask which functions or methods might already exist to ...
🌐
AskPython
askpython.com › python › string › python-replace-function
Python replace() function - AskPython
May 21, 2026 - The simplest use case is swapping one substring for another. Python scans the entire string and replaces every match it finds. The variable holding the original string remains unchanged since strings are immutable.
🌐
Real Python
realpython.com › replace-string-python
How to Replace a String in Python – Real Python
October 22, 2025 - As you can see, you can chain .replace() onto any string and provide the method with two arguments. The first is the string that you want to replace, and the second is the replacement. Note: Although the Python shell displays the result of .replace(), the string itself stays unchanged.
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › python-pandas-series-str-replace-to-replace-text-in-a-series
Python | Pandas Series.str.replace() to replace text in a series - GeeksforGeeks
July 11, 2025 - Example: The .str.replace() method is a part of the Pandas String Handling capabilities. This let users to replace occurrences of a specified substring with another substring in text data contained within a Pandas Series.
🌐
Python
docs.python.org › 3 › library › string.html
string — Common string operations
The field_name is optionally followed by a conversion field, which is preceded by an exclamation point '!', and a format_spec, which is preceded by a colon ':'. These specify a non-default format for the replacement value. See also the Format specification mini-language section. The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument. An arg_name is treated as a number if a call to str.isdecimal() on the string would return true.
🌐
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 a…