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:
tuple
are much less complex objects thandict
and there is no real need fordict
- 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.