Consider the following examples:
string_now = 'apple and avocado'
stringthen = string_now.swap('apple', 'avocado') # stringthen = 'avocado and apple'
and:
string_now = 'fffffeeeeeddffee'
stringthen = string_now.swap('fffff', 'eeeee') # stringthen = 'eeeeefffffddffee'
Approaches discussed in Swap character of string in Python do not work, as the mapping technique used there only takes one character into consideration. Python's built-in str.maketrans() also only supports one-character translations, as when I try to do multiple characters, it throws the following error:
Traceback (most recent call last):
File "main.py", line 4, in <module>
s.maketrans(mapper)
ValueError: string keys in translate table must be of length 1
A chain of replace() methods is not only far from ideal (since I have many replacements to do, chaining replaces would be a big chunk of code) but because of its sequential nature, it will not translate things perfectly as:
string_now = 'apple and avocado'
stringthen = string_now.replace('apple', 'avocado').replace('avocado', 'apple')
gives 'apple and apple' instead of 'avocado and apple'.
What's the best way to achieve this?