• 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')

     

  • 相关阅读:
    (DDD)仓储的思考
    js模块化
    elasticsearch 集群
    多线程和多进程模型
    WebAPI 用ExceptionFilterAttribute实现错误(异常)日志的记录(log4net做写库操作)
    WebAPI 用ActionFilterAttribute实现token令牌验证与对Action的权限控制
    jekyll博客安装
    bootstrap+jQuery.validate
    cygwin的163镜像(转)
    ExecutorService invokeAll 实例(转)
  • 原文地址:https://www.cnblogs.com/wangsl1204/p/10374197.html
Copyright © 2020-2023  润新知