string_utils#

String utilities for KnotPy.

Currently includes: - abcABC: convenience alphabet string (a–z + A–Z). - multi_replace: repeated multi-substring replacement.

Functions

multi_replace(text, *replacements)

Repeatedly apply multiple substring replacements until no change occurs.

multi_replace(text, *replacements)#

Repeatedly apply multiple substring replacements until no change occurs.

Replacements can be given as (old, new) tuples or {old: new} dicts. All replacements are applied in sequence per pass, and the process repeats until the text stops changing or max_passes is reached.

Note

If your replacements create a cycle (e.g., (“A”,”B”) and (“B”,”A”)), the function would otherwise loop forever. max_passes prevents that; if reached, the current text is returned.

Parameters:
  • text (str) – Input string to transform.

  • *replacements (tuple[str, str] | dict[str, str]) – One or more (old, new) tuples or {old: new} dicts.

  • max_passes – Safety cap on the number of full replacement passes.

Returns:

The transformed string.

Return type:

str

Examples

>>> multi_replace("AAAABC", ("AA", "a"), {"B": "b"}, ("C", "c"))
'aabc'  # first pass: AAAABC -> aAABC -> aaABC -> aabC -> aab c
        # second pass: aabc (no change) -> stop
>>> multi_replace("foo-bar", ("foo", "bar"), ("bar", "baz"))
'bar-baz'