字符串在python中使用我的unicode?

kn3*_*n3l 8 python unicode python-3.x

Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> str_version = '??????'
>>> type(str_version)
<class 'str'>
>>> print (str_version)
??????
>>> unicode_version = '??????'.decode('utf-8')
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    unicode_version = '??????'.decode('utf-8')
AttributeError: 'str' object has no attribute 'decode'
>>> 
Run Code Online (Sandbox Code Playgroud)

我的unicode字符串有什么问题?

Bra*_*des 10

你的字符串没有错!你只是困惑encode()decode().字符串是有意义的符号.把它变成可能被存储在文件中或传输因特网字节,使用encode()编码像UTF-8.每个编码是用于将有意义的符号转换为平坦的输出字节的方案.

当时间恰好相反 - 从文件或套接字中取出一些原始字节并将它们转换为字母和数字等符号 - 您将使用Python 3中的字节串方法解码字节decode().

>>> str_version = '??????'
>>> str_version.encode('utf-8')
b'\xe1\x9e\x93\xe1\x9e\x99\xe1\x9f\x84\xe1\x9e\x94\xe1\x9e\xb6\xe1\x9e\x99'
Run Code Online (Sandbox Code Playgroud)

看到那么长的字节行?这些是UTF-8用于表示字符串的字节,如果您需要通过网络传输字符串,或将它们存储在文档中.还有许多其他编码在使用,但它似乎是最受欢迎的.每个编码都可以将有意义的符号(如ន和turn)转换为字节 - 计算机与之通信的小8位数字.

>>> rawbytes = str_version.encode('utf-8')
>>> rawbytes
b'\xe1\x9e\x93\xe1\x9e\x99\xe1\x9f\x84\xe1\x9e\x94\xe1\x9e\xb6\xe1\x9e\x99'
>>> rawbytes.decode('utf-8')
'??????'
Run Code Online (Sandbox Code Playgroud)


Ign*_*ams 7

你正在阅读2.x文档.str.decode()(和bytes.encode())被放弃在3.x. 并且str已经是Unicode字符串; 没有必要解码它.