zoukankan      html  css  js  c++  java
  • python编码

    参考文章:https://blog.csdn.net/yanghuan313/article/details/63262477

    python编码:encode()

    将Unicode字符按照编码规则(如UTF-8)编成字节序列。

    >>> a = u"测试"
    >>> a.encode("UTF-8")
    'xe6xb5x8bxe8xafx95'

    python解码:decode()

    将字节序列按照编码规则(如UTF-8)解释成unicode。

    >>> a = b"测试"
    >>> a.decode("GBK")
    u'u5a34u5b2du762f'

      默认编码(str)   总结
    python2  bytes(字节字符串)  unicode(文本字符串) str 对象有一个encode方法,bytes 对象有一个decode方法,str有个encode()方法,unicode有个decode()方法,但永远不要使用它们。
    python3

    Unicode(文本字符串)

    bytes(字节字符串)

    str 对象有一个encode方法,bytes 对象有一个decode方法

     

    # python2
    >>> a = "测试"
    >>> type(a)
    <type 'str'>
    >>> a.decode("GBK")
    u'u5a34u5b2du762f'
    >>> type(a.decode("GBK"))
    <type 'unicode'>
    
    >>> b = u"测试"
    >>> type(b)
    <type 'unicode'>
    >>> b.encode("GBK")
    'xb2xe2xcaxd4'
    >>> type(b.encode("GBK"))
    <type 'str'>

    # python3

    >>> a = "测试"
    >>> type(a)
    <class 'str'>
    >>> a.encode("UTF-8")
    b'xe6xb5x8bxe8xafx95'
    >>> type(a.encode("UTF-8"))
    <class 'bytes'>
    >>>
    >>> b = b"测试"
    File "<stdin>", line 1
    SyntaxError: bytes can only contain ASCII literal characters.
    >>> b = b"wangsl"
    >>> type(b)
    <class 'bytes'>
    >>> b.decode("UTF-8")
    'wangsl'
    >>> type(b.decode("UTF-8"))
    <class 'str'>

     # b''表示bytes(二进制)类型;str表示unicode(字符)类型
    # 如下是互相转换方式
    b'' = str.encode('utf-8')
    str = b''.decode('utf-8')

     

  • 相关阅读:
    企业级 SpringBoot 教程 (九)springboot整合Redis
    03 网格系统
    02 表单
    01 排版
    客户端调用webSerices
    sql 一行转多行
    sql 多行转一行
    时间差计算 Stopwatch
    sql 游标
    Linq连接查询
  • 原文地址:https://www.cnblogs.com/wangsl1204/p/10374197.html
Copyright © 2011-2022 走看看