Python中的Unicode字符串语法

Ser*_*gey 4 python unicode python-3.x

官方Python教程声明Python中的Unicode字符串可以像这样使用:

u'Hello World !'
Run Code Online (Sandbox Code Playgroud)

但是当我把它放到IDLE - Python 3.2的Python GUI时,它给了我一个语法错误.俄语和中文文本也可以成功存储在Python字符串中,所以我猜它们已经是Unicode了.

你能解释一下发生了什么吗?

Ser*_*lis 7

默认情况下,python 3.2使用unicode字符串,因此u不再需要.

如果要编码和解码字符串,则应使用:

encoded = "unicodestring".encode("UTF8")

decoded = s.decode("UTF8")
Run Code Online (Sandbox Code Playgroud)

Python的documetation指出:

Python 3.0使用文本和(二进制)数据的概念而不是Unicode字符串和8位字符串.所有文本都是Unicode; 但编码的Unicode表示为二进制数据.用于保存文本的类型是str

你不能再使用u"..."文字来表示Unicode文本.但是,必须对二进制数据使用b"..."文字.