python中unicode字符串前缀u

python2.x中,unicode字符串需要在字符串前加u来表示,比如

str=u'汉字'

而在python3.x中,unicode字符串已经是默认格式,因此不再需要加u,如果你加了u,会报语法错误:

str=u'汉字'

SyntaxError: invalid syntax

注意:(1)当文件使用utf-8编码时:非unicode字符中一个汉字的长度是3,unicode一个汉字长度是1;
           (2)当文件使用gb2312 时, 非unicode字符中一个汉字的长度是2,unicode一个汉字长度是1;
见下边代码:

脚本1
# -*- coding: utf-8 -*-  
unicode = u'我'
str = '我'   
print len(unicode),len(str)   #输出 1    3  


脚本2
# -*- coding: gb2312 -*-   
unicode = u'我'   
str = '我' 
print len(unicode),len(str)   #输出 1    2 

转自: http://blog.163.com/yang_jianli/blog/static/1619900062013830104610633/

原文地址:https://www.cnblogs.com/loayi/p/7769407.html