zoukankan      html  css  js  c++  java
  • Python字符编码转换Unicode和str

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

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

    ## str 我们平时写的用引号括起来的字符串都是str类型的。
    >>> x = '哈哈'
    >>> x
    'xb9xfexb9xfe'
    ### 根据上面的打印结果,可以知道str类型的x存的其实是二进制序列,而非字符串。为什么会出现这种情况呢?我们赋给x的明明是字符串。
    其实很简单,x经过了一次隐形的编码过程encode()。应该采用的是系统默认编码方案。 
    
    ## unicode 如果在引号的前面加上字符u,那么我们就得到一个unicode字符串:
    >>> x = u'哈哈'
    >>> x
    u'u54c8u54c8'
    ### unicode对象保存的是字符串本身,而非二进制序列。比如程序中的unicode字符串中包含两个U+54c8字符。
    
    ### 为了避免错误,在写入文件之前,应该用utf-8或者gbk编码方案对unicode字符串编码
    >>> x = u'哈哈'
    >>> x
    u'u54c8u54c8'
    >>> f = open('test.txt', 'w');
    >>> x = x.encode('utf-8') #unicode -> str
    >>>x
    'xe5x93x88xe5x93x88'
    >>> 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
    
    
  • 相关阅读:
    Notes of the scrum meeting(12.7)
    Notes of the scrum meeting(12.5)
    事后分析报告(M1阶段)
    锁屏软件发布说明
    Android 锁屏软件MemoryDebris测试报告
    锁屏软件功能介绍
    Notes of the scrum meeting(11/4)
    Notes of the scrum meeting(11/3)
    Notes of the scrum meeting(11/2)
    SCRUM 12.17
  • 原文地址:https://www.cnblogs.com/yes5144/p/11523516.html
Copyright © 2011-2022 走看看