Feature Proposal: Multi-String Replacement Using a Dictionary in the .replace() Method

This is closely related to string improvements myself and @Nineteendo were working on.

I don’t think doing a naive:

s.replace(...).replace(...)

is the best way to go. Instead, efficient version (which allows swapping) is possible and is a natural consequence of: tuple find

Ideally, this will be easy and natural to implement after:
a) gh-119702: New dynamic algorithm selection for string search (+ `rfind` alignment) by dg-pb · Pull Request #120025 · python/cpython · GitHub
b) Add tuple support to more str functions - #136 by dg-pb
c) String API changes

After these, implementing multi-pattern replace, split and similar will be straight forward.

I think it would be good to keep API consistent. And currently it seems that string methods tend to use tuple arguments. Such as str.endswith and upcomming str.find.

And I think it would work well, as:

  1. tuple are much less complex objects than dict and there is no real need for dict
  2. It would provide extra convenience replacing many substrings with a single one (see below)

Keeping old and new for this would look like:

string = 'a_b_c'
string.replace(('a', 'b'), ('z', 'z'))    # 'z_z_c'
string.replace(('a', 'b'), 'z')           # 'z_z_c'
string.replace(('a', 'b'), ('b', 'a'))    # 'b_a_c'

If someone prefers dictionary, then one can simply do:

d = {'a': 'b', 'b': 'a'}
string.replace(tuple(d.keys()), tuple(d.values()))

Or even implement it in C if that is highly desirable.

The whole work has been stuck on gh-119702: New dynamic algorithm selection for string search (+ `rfind` alignment) by dg-pb · Pull Request #120025 · python/cpython · GitHub for quite a while now. So if someone would like to help move things forward here, next step is coredev review.

Utilizing Python version 3.12.7

a = “hello”
a = a.replace({“l”: “X”, “h”: “X”})

line 2, in
a = a.replace({“l”: “X”, “h”: “X”})
TypeError: replace expected at least 2 arguments, got 1

This thread is about a proposal for a new feature. It doesn’t exist yet, and if it does it may take a different form from what was proposed.