是否可以使用 maketrans 将一个字符替换为两个字符?
Is it possible replace one character by two using maketrans?
我想用 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
是的,这是可能的。您需要提供 dict
作为 maketrans()
的参数。如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)
输出
vaere
我想用 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
是的,这是可能的。您需要提供 dict
作为 maketrans()
的参数。如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)
输出
vaere