zoukankan      html  css  js  c++  java
  • 字符编码

    转载自博客:http://blog.csdn.net/zbyufei/article/details/5856730

    1.unicode 缺失转换

    如把 "/u5317/u4eac"转化成 gb18030的北京

    s="/u5317/u4eac"
    s=eval("u'%s'"% s)
    s.encode('gb18030')
    print s

    2.unicode 转换为其它编码(GBK, GB2312等)

    # -*- coding=gb2312 -*-
    a=u"中文"
    a_gb2312=a.encode('gb2312')
    print a_gb231

    3.其它编码(utf-8,GBK)转换为unicode

    例如:a为gb2312编码,要转为unicode. unicode(a, 'gb2312')或a.decode('gb2312')
    # -*- coding=gb2312 -*-
    a=u"中文"
    a_gb2312= a.encode('gb2312')
    print a_gb2312

    a_unicode=a_gb2312.decode('gb2312')
    assert(a_unicode== a)
    a_utf_8= a_unicode.encode('utf-8')
    print a_utf_8

    4.非unicode编码之间的转换

    编码1(GBK,GB2312)  转换为 编码2(utf-8,utf-16,ISO-8859-1), 可以先转为unicode再转为编码2 ,如gb2312转utf-8

    # -*- coding=gb2312 -*-
    a=u"中文"
    a_gb2312=a.encode('gb2312')
    print a_gb2312

    a_unicode=a_gb2312.decode('gb2312')
    assert(a_unicode== a)
    a_utf_8=a_unicode.encode('utf-8')
    print a_utf_8


    5.判断字符串的编码

    isinstance(s, str) 用来判断是否为一般字符串   isinstance(s, unicode) 用来判断是否为unicode  如果一个字符串已经是unicode了,再执行unicode转换有时会出错(并不都出错)  ,下面代码为将任意字符串转换为unicode

    def u (s , encoding ):
        if isinstance (s , unicode ):
            return s
        else :
            return unicode (s , encoding )

    6.unicode 与其它编码之间的区别

    为什么不所有的文件都使用unicode,还要用GBK,utf-8等编码呢? unicode可以称为抽象编码,也就是它只是一种内部表示,一般不能直接保存。 保存到磁盘上时,需要把它转换为对应的编码,如utf-8和utf-16。

    7.其它方法

    除上以上的编码方法,在读写文件时还可以使用codecs的open方法在读写时进行转换。

    8 . python 3 默认字符编码为 Unicode

    9. GBK 转化为 Utf-8 : GBK decode to Unicode , then encode to Utf-8

    '''
    gbk 转换为 utf-8
    decode("gbk")---> Unicode
    encode("utf-8")---->Utf-8
    '''
  • 相关阅读:
    1094. Car Pooling
    121. Best Time to Buy and Sell Stock
    58. Length of Last Word
    510. Inorder Successor in BST II
    198. House Robber
    57. Insert Interval
    15. 3Sum java solutions
    79. Word Search java solutions
    80. Remove Duplicates from Sorted Array II java solutions
    34. Search for a Range java solutions
  • 原文地址:https://www.cnblogs.com/frankb/p/6200913.html
Copyright © 2011-2022 走看看