【问题标题】:What is the proper way to use str.decode and unicode.encode?使用 str.decode 和 unicode.encode 的正确方法是什么?
【发布时间】:2010-01-08 06:51:09
【问题描述】:

str.decode 和 unicode.encode 的正确使用方法是什么?

例如。

print str.decode
print unicode.encode

【问题讨论】:

  • -1:应该在“pleasedomyhomeworkforme.com”上发布
  • 谁能给你代码?你想要代码还是写代码的人的名字?

标签: python


【解决方案1】:

Ignacio 的示例是正确的,但取决于您的控制台是否能够显示 Unicode 字符,而在 Windows 上通常不能。这是同样的事情,只有安全的字符串转义(reprs):

>>> '\xe3\x81\x82'.decode('utf-8')    # three top-bit-set bytes, representing one character
u'\u3042'                             # Hiragana letter A

>>> u'\u3042'.encode('shift-jis')
'\x82\xa0'                            # only requires two bytes in the Shift-JIS encoding

>>> unicode('\x82\xa0', 'shift-jis')  # alternative way of doing a decode
u'\u3042'

当你写信给例如。一个文件或通过网络服务器,或者您在控制台支持 UTF-8 的另一个操作系统上,这更容易一些。

【讨论】:

    【解决方案2】:
    print 'あ'.decode('utf-8')
    print repr(u'あ'.encode('shift-jis'))
    

    【讨论】:

    • 文件 "D:\zjm_code\a.py",第 4 行 SyntaxError: Non-ASCII character '\xe3' in file D:\zjm_code\a.py on line 4,但未声明编码;详情见python.org/peps/pep-0263.html
    • 阅读该 URL 并修复您的来源。
    • @zjm1126:插入第一行:# coding: utf-8
    • 回溯(最近一次调用最后):文件“D:\zjm_code\a.py”,第 5 行,在 中 print '\xe3\x81\x82'.decode('utf- 8') UnicodeEncodeError: 'ascii' codec can't encode character u'\u3042' in position 0: ordinal not in range(128)
    • @zjm1126:正如您之前所建议的,使用 print repr(some_unicode) 而不是 print some_unicode ... Windows 标准输出无法识别 unicode
    【解决方案3】:
    >>> unicode.encode(u"abcd","utf8")
    'abcd' #unicode string u"abcd" got encoded to UTF-8 encoded string "abcd"
    
    >>> str.decode("abcd","utf8")
    u'abcd' #UTF-8 string "abcd" got decoded to python's unicode object u"abcd"
    >>>
    

    【讨论】:

    • 没有理由在类上调用它们,因为它们可以(如果不是更多)在实例上轻松调用。
    猜你喜欢
    • 2019-05-17
    • 2014-12-08
    • 1970-01-01
    • 2023-03-15
    • 2011-11-11
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多