Skip to content

Instantly share code, notes, and snippets.

@mrtj
Created January 28, 2025 14:25
Show Gist options
  • Save mrtj/37def974a74f256e2e3d24bb8f1761e6 to your computer and use it in GitHub Desktop.
Save mrtj/37def974a74f256e2e3d24bb8f1761e6 to your computer and use it in GitHub Desktop.
Replace multiple old-new pairs in string
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