gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:20:25 26 4
gpt4 key购买 nike

我想用 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

最佳答案

是的,这是可能的。您需要提供一个 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

关于python - 是否可以使用 maketrans 将一个字符替换为两个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53897804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com