Created
January 28, 2025 14:25
-
-
Save mrtj/37def974a74f256e2e3d24bb8f1761e6 to your computer and use it in GitHub Desktop.
Replace multiple old-new pairs in string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Iterable | |
from functools import reduce | |
def replace_all(text: str, table: Iterable[tuple[str, str]]) -> str: | |
""" Replaces multiple strings in a string. | |
Usage: | |
```python | |
replace_all("Hello World", [("Hello", "Hi"), ("World", "Earth")]) | |
# 'Hi Earth' | |
``` | |
""" | |
return reduce(lambda s, pair: s.replace(*pair), table, text) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment