【问题标题】:Python 3.x: Using string.maketrans() in order to create a unicode-character transformationPython 3.x:使用 string.maketrans() 来创建 unicode 字符转换
【发布时间】: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


    【解决方案1】:

    你需要使用str.maketrans(),它接受两个str作为参数。

    >>> frm = 'acdefhnoprstuw'
    >>> to = 'אקדיפהנופרסתאו'
    >>> trans_table = str.maketrans(frm, to)
    >>> hebrew_phrase = 'fear cuts deeper than swords'.translate(trans_table)
    >>> hebrew_phrase
    'פיאר קאתס דייפיר תהאנ סוורדס'
    

    String.maketrans 仍然存在于 Python 3.1 中,但这只是因为他们错过了将其移至 3.0 中的 bytes.maketrans() 。它已在 3.1 中被弃用,在 3.2 中已消失。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-17
    • 2018-04-29
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 2021-11-17
    相关资源
    最近更新 更多