最新公告
  • 欢迎您光临知事网软件APP资源下载站,一个优质的手机App应用商店和网站源码基地。欢迎加入永久SVIP
  • Python中decode(解码)和encode(编码)如何使用?

    正文概述 知事网   2020-12-14 11:12:19   297

    在python中,我们通常使用的是unicode编码,但是日常文本使用各类编码为 utf-8 ,编码的类型不一样,就容易造成乱码。为了避免读写操错误,我们需要进行转码则需要decode(解码)和encode(编码)方法。

    1、decode的作用是将其他编码的字符串转换成unicode编码

    将 bytes 类型转换为 str 类型(b.decode())

    2、encode的作用是将unicode编码转换成其他编码的字符串

    将 str 类型转换为 bytes 类型(str.encode())

    将 str 类型转换为 bytes 类型(str.)

    bytes to str

    3、使用

    字符串通过编码转换成字节码,字节码通过解码成为字符串

    encode:str –> bytes

    decode:bytes – > str

    直接上代码:

    import sys
    
    print('目前系统的编码为:',sys.getdefaultencoding())
    
    name='小明'
    
    print(type(name))#首先我们来打印下转码前的name类型,因为它是str,所以可以通过encode来进行编码
    
    name1=name.encode('utf-8')
    
    print(name1)

    输出

    目前系统的编码为: utf-8
    
    <class 'str'>
    
    b'xe5xb0x8fxe6x98x8e'

    以上就是Python中decode(解码)和encode(编码)的使用方法,大家可以直接套用使用哦~


    知事网 » Python中decode(解码)和encode(编码)如何使用?

    发表评论

    还没有评论,快来抢沙发吧!

    [!--temp.right--]
    请选择支付方式
    ×
    余额支付
    ×
    微信扫码支付 0 元