【发布时间】:2012-04-26 07:52:36
【问题描述】:
我想写如下代码:
import string
frm = b'acdefhnoprstuw'
to = 'אקדיפהנופרסתאו'
trans_table = string.maketrans(frm, to)
hebrew_phrase = 'fear cuts deeper than swords'.translate(trans_table)
上面的代码不起作用,因为string.maketrans(frm, to) 的to 参数必须是字节序列,而不是字符串。问题是字节序列只能包含 ASCII 文字字符。因此,我无法进行将英语字符串翻译成希伯来语字符串的转换。原因是string.maketrans() 重新运行了一个字节对象。
有没有一种优雅的方式来为我的任务使用 string.maketrans() 和 translate() 函数(或使用 unicode 的等效函数)?
【问题讨论】:
标签: python string unicode python-3.x