Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7202306
  • 博文数量: 510
  • 博客积分: 12019
  • 博客等级: 上将
  • 技术积分: 6836
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-01 16:46
文章分类

全部博文(510)

文章存档

2022年(2)

2021年(6)

2020年(59)

2019年(4)

2018年(10)

2017年(5)

2016年(2)

2015年(4)

2014年(4)

2013年(16)

2012年(47)

2011年(65)

2010年(46)

2009年(34)

2008年(52)

2007年(52)

2006年(80)

2005年(22)

分类: Python/Ruby

2020-03-20 10:08:27

 参考链接1:https://blog.csdn.net/VictoriaW/article/details/75314737


参考链接2:https://blog.csdn.net/sheldonwong/article/details/86684761
Unicode和str


## str 我们平时写的用引号括起来的字符串都是str类型的。
>>> x = '哈哈'
>>> x
'\xb9\xfe\xb9\xfe'
### 根据上面的打印结果,可以知道str类型的x存的其实是二进制序列,而非字符串。为什么会出现这种情况呢?我们赋给x的明明是字符串。
其实很简单,x经过了一次隐形的编码过程encode()。应该采用的是系统默认编码方案。 


## unicode 如果在引号的前面加上字符u,那么我们就得到一个unicode字符串:
>>> x = u'哈哈'
>>> x
u'\u54c8\u54c8'
### unicode对象保存的是字符串本身,而非二进制序列。比如程序中的unicode字符串中包含两个U+54c8字符。


### 为了避免错误,在写入文件之前,应该用utf-8或者gbk编码方案对unicode字符串编码
>>> x = u'哈哈'
>>> x
u'\u54c8\u54c8'
>>> f = open('test.txt', 'w');
>>> x = x.encode('utf-8') #unicode -> str
>>>x
'\xe5\x93\x88\xe5\x93\x88'
>>> f.write(x)
Unicode strings can be encoded in plain strings in a variety of ways, according to whichever encoding you choose:
Unicode字符串可以用多种方式编码为普通字符串, 依照你所选择的编码(encoding):


   1 #将Unicode转换成普通的Python字符串:"编码(encode)"
   2 unicodestring = u"Hello world"
   3 utf8string = unicodestring.encode("utf-8")
   4 asciistring = unicodestring.encode("ascii")
   5 isostring = unicodestring.encode("ISO-8859-1")
   6 utf16string = unicodestring.encode("utf-16")
   7 
   8 
   9 #将普通的Python字符串转换成Unicode: "解码(decode)"
  10 plainstring1 = unicode(utf8string, "utf-8")
  11 plainstring2 = unicode(asciistring, "ascii")
  12 plainstring3 = unicode(isostring, "ISO-8859-1")
  13 plainstring4 = unicode(utf16string, "utf-16")
  14 
  15 assert plainstring1==plainstring2==plainstring3==plainstring4
阅读(1388) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~