Looks like a good opportunity to use a loop:

mapping = { 'A':'1', 'B':'2', 'C':'3', 'D':'4', 'E':'5'}
for k, v in mapping.iteritems():
    my_string = my_string.replace(k, v)

A faster approach if you don't mind the parentheses would be:

mapping = [ ('A', '1'), ('B', '2'), ('C', '3'), ('D', '4'), ('E', '5') ]
for k, v in mapping:
    my_string = my_string.replace(k, v)
Answer from Rick Copeland on Stack Overflow
🌐
Note.nkmk.me
note.nkmk.me › home › python
Extract and Replace Elements That Meet the Conditions of a List of Strings in Python | note.nkmk.me
May 19, 2023 - To replace the whole element containing a specific string, use the in operator to extract it and apply conditional expressions (ternary operator), formatted as X if condition else Y. ... Use conditional expressions for the expression part of ...
Discussions

A list of string replacements in Python - Stack Overflow
Copymapping = [ ('A', '1'), ('B', ... = my_string.replace(k, v) ... It's odd; that's the way I'd write it, because the problem is all about mapping from one character to another. But really, you're not using the dict as a dict; you're using it as a list of tupl... More on stackoverflow.com
🌐 stackoverflow.com
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 - Substitute patterns with values from lists - Code Review Stack Exchange
Another alternative is to define the function so that the last replacement value for a key is never popped; there is always at least one element in the value list for any key. This remaining value will be used for all subsequent replacements. In that way, you can replace all occurrences of a string ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
November 22, 2025
Trying to replace characters in a list of strings?
Strings are immutable, replace doesn't operate in place but returns a new string. x = x.replace("cy","fi") Note that the whole thing can be done as a list comprehension: newlist = [ x.replace("cy","fi") for x in list] Also, don't call your own variables 'list'. More on reddit.com
🌐 r/learnpython
9
10
January 9, 2023
🌐
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....
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-replace-substring-in-list-of-strings
Replace substring in list of strings - Python - GeeksforGeeks
July 11, 2025 - The replace() function replaces all occurrences of "world" with "universe" in each string. List comprehension iterates through the list and applies replace() to every string.
🌐
Analytics Vidhya
analyticsvidhya.com › home › how to replace values in a list in python?
How to Replace Values in a List in Python? - Analytics Vidhya
April 23, 2025 - A. Yes, you can replace a value in a list in Python using various methods such as indexing, list comprehension, built-in functions like replace() for strings within lists, or functional programming tools like map().
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-replace-values-in-a-list-in-python
How to Replace Values in a List in Python? - GeeksforGeeks
Since strings in Python are immutable, any modification requires creating a new string with the desired changes. For example, if we have a string like "Hello, World!", we mi ... Lists in Python have various built-in methods to remove items such as remove, pop, del and clear methods.
Published: January 4, 2025
🌐
stataiml
stataiml.com › posts › 35_find_replace_string_python_list
Find and Replace Values in List in Python - stataiml
May 3, 2024 - You can find and replace string values in a list using a list comprehension or map() function in Python.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-replace-values-in-a-list-in-python
Replace Values in a List in Python - GeeksforGeeks
It works when the index of the element to be replaced is already known. ... This method checks every element in the list and replaces only those values that satisfy a given condition, while rebuilding the list in a single expression using list ...
Published: January 12, 2026
🌐
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 a unnecessary performance hit if the string is large or the call is the calls ...
🌐
datagy
datagy.io › home › python posts › python: replace item in list (6 different ways)
Python: Replace Item in List (6 Different Ways) • datagy
August 12, 2022 - Learn how to replace an item or items in a Python list, including how to replace at an index, replacing values, replacing multiple values.
🌐
pythontutorials
pythontutorials.net › blog › find-and-replace-string-values-in-list
How to Find and Replace String Values in a Python List: Replace [br] Substring with Space Example — pythontutorials.net
They’re ideal for simple transformations, such as replacing substrings in each element of a list. For each string s in original_list, we use the str.replace(old, new) method to replace [br] with a space.
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to replace strings in python lists
5 Best Ways to Replace Strings in Python Lists - Be on the Right Side of Change
February 16, 2024 - The map() function applies a given function to all items in an input list. You can use it in conjunction with a lambda function to replace strings in a list, though it requires conversion back to a list type.
Top answer
1 of 4
7

I would prefer to take Iterable[tuple[str, Iterable[str]]] rather than dict[str, list[str]] for two reasons:

  1. Iterable allows for a wider range of inputs than binding to concrete types.

  2. Adding .items() in the function call is largly an irrelevant change.

    print(replace_in_string(TextFileContent, replacements.items()))
    
terms = copy.deepcopy(replacements)

IIRC deep copy will copy all of the values in the dictionary, even the strings. We can reduce the memory usage by only 'copying' the dictionary and setting the values to iterators (iter) and then advancing the iterator in replace_func.

terms = {k: iter(vs) for k, vs in replacements.items()}
def replace_func(m):
    return next(terms[m.group()])
2 of 4
6

Tests

It's nice to see that you have included various tests to verify that replace_in_string works as expected.

Docstring

Its great that you have provided a docstring, but I think it could be a bit more descriptive (argument string is not even mentioned). For example:

"""
      string: a str.
replacements: a dictionary whose keys are strings and whose values
              are lists of string replacements.

For each key in replacements, search string for occurrences
of that key replacing each occurrence with successive elements
of the key's value.
"""

Methodology

Using re.sub seems to be the best approach to string replacement.

Will you ever have a situation where you might wish to ensure that a string being replaced is on a word boundary? In that case you could surround the key with r'\b', but then calling re.escape on the key would not work. So your keys will already need to be regular expressions that do not need escaping. Would it be useful to have an additional argument, e.g. is_regex, that defaults to False but when True means that the keys are already regular expressions that should not be escaped?

Recommendation and Alternatives

I think it's indicative of something being amiss if there are too few values for any key in replacements. Consequently, in your alternative implementation of replace_func my preference would be for you to either raise an Exception or at least issue a warning for this situation.

An alternative would be to provide an extra, optional argument to your function, e.g. strict_mode=True, which causes behavior as just described but when False, issues no warnings or exceptions.

Another alternative is to define the function so that the last replacement value for a key is never popped; there is always at least one element in the value list for any key. This remaining value will be used for all subsequent replacements. In that way, you can replace all occurrences of a string with the same value just by having a replacement list consisting of a single element. The only error situation now would be to define an empty list as the value for a key.

🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python replace values in list with examples
Python Replace Values in List With Examples - Spark By {Examples}
May 31, 2024 - How to replace values or elements in list in Python? You can replace a list in python by using many ways, for example, by using the list indexing, list
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-replace-substrings-from-string-list
Replace Substrings from String List - Python - GeeksforGeeks
July 12, 2025 - This approach iterates over the replacement dictionary and applies .replace() to each string. While more readable and simple, it loops multiple times and making it less efficient for large datasets. Python · # list of strings a = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science'] # list of word replacements b = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']] replace_map = dict(b) # convert `b` to dictionary for key, val in replace_map.items(): a = [ele.replace(key, val) for ele in a] print(a) Output ·
🌐
Python Pool
pythonpool.com › home › tutorials › replace items in a python list: index, loop, map(), and slices
Replace Items in a Python List: Index, Loop, map(), and Slices
July 13, 2026 - Check duplicate values, nested data, bounds, aliasing, and whether a new list is safer than mutation. When the match rule is more complicated than equality, put it in a function or a clearly named condition. values = [3, 10, 15, 22] updated = [0 if value % 5 == 0 else value for value in values] print(updated) This replaces values divisible by five and preserves the order of every other item. A predicate makes the behavior testable and prevents a broad string replacement from changing values that only happen to contain the same text.
🌐
Stack Overflow
stackoverflow.com › questions › 72378766 › how-to-replace-a-character-within-a-string-in-a-list
python - How to replace a character within a string in a list? - Stack Overflow
use .replace('.') to replace a period from your text example. w3schools.com/python/ref_string_replace.asp ... Save this answer. ... Show activity on this post. Modifying strings is not efficient in python because strings are immutable. And when you modify them, the indices may become out of range at the end of the day. Copylist_ = ["string1.", "string2."] for i, s in enumerate(list_): l[i] = s.replace('.', '')