How do I get str.translate to work with Unicode strings?

前端 未结 7 955
孤城傲影
孤城傲影 2020-12-01 00:17

I have the following code:

import string
def translate_non_alphanumerics(to_translate, translate_to=\'_\'):
    not_letters_or_digits = u\'!\"#%\\\'()*+,-./:         


        
7条回答
  •  执念已碎
    2020-12-01 00:20

    I found that where in python 2.7, with type str, you would write

    import string
    table = string.maketrans("123", "abc")
    print "135".translate(table)
    

    whereas with type unicode you would say

    table = {ord(s): unicode(d) for s, d in zip("123", "abc")}
    print u"135".translate(table)
    

    In python 3.6 you would write

    table = {ord(s): d for s, d in zip("123", "abc")}
    print("135".translate(table))
    

    maybe this is helpful.

提交回复
热议问题