我想用ae替换æ字符。我如何获得它?这是我对maketrans
和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)
它会产生错误:
TypeError: maketrans() argument 2 must be str, not tuple
ValueError: the first two maketrans arguments must have equal length
答案 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