是否可以使用maketrans将一个字符替换为两个字符?

时间:2018-12-22 17:18:46

标签: python string translation

我想用ae替换æ字符。我如何获得它?这是我对maketranstranslate的尝试:

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)

它会产生错误:

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

1 个答案:

答案 0 :(得分:2)

是的,有可能。您需要提供dict作为maketrans()的参数。如the docs

中所述
  

如果只有一个参数,则必须是将Unicode序号(整数)或字符(长度为1的字符串)映射到Unicode序号,字符串(任意长度)或无的字典。然后,字符键将转换为普通字符。

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

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

输出

vaere