Is it possible replace one character by two using maketrans?

Question:

I want to replace æ character with ae. How can I obtain it? Here is my try with maketrans and translate:

word = 'være'
letters = ('å','ø', 'æ')
replacements = ('a','o','ae')

table = word.maketrans(letters, replacements)
#table = word.maketrans(''.join(letters),''.join(replacements))
word_translated = word.translate(table)
print(word_translated)

It generates errors:

TypeError: maketrans() argument 2 must be str, not tuple
ValueError: the first two maketrans arguments must have equal length
Asked By: Ethr

||

Answers:

Yes, it’s possible. You need to supply a dict as argument to maketrans(). As stated in the docs

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals.

word = 'være'
letters = ('å','ø', 'æ')
replacements = ('a','o','ae')

table = word.maketrans(dict(zip(letters, replacements)))
word_translated = word.translate(table)
print(word_translated)

output

vaere
Answered By: buran
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.