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 builtin str.maketrans()
also only supports one-character translations, as when I try to do multiple characters, it throws the following error:
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?
\n
?'applemon'.swap('apple', 'lemon')
produce?'applemon'.swap('apple', 'mon')
or'applemon'.swap('app', 'lemon')
. But it sure is a very interesting case to look at.