zoukankan      html  css  js  c++  java
  • Python

    decode和encode的区别和介绍

     by.decode(encoding='UTF-8',errors='strict') 

     str.encode(encoding='UTF-8',errors='strict') 

    • 显而易见decode是解码,encode是编码
    • 解码代表bytes类型转成str类型
    • 编码代表str类型转成bytes类型
    • 而bytes类型的数据一般在写入文件时需要用到

    直接上代码

     1 #!/usr/bin/env python
     2 # -*- coding: utf-8 -*-
     3 
     4 """
     5 __title__  = 
     6 __Time__   = 2020/2/21 15:56
     7 
     8 """
     9 # bytes转字符串方式一
    10 b = b'xe9x80x86xe7x81xab'
    11 string = str(b, 'utf-8')
    12 print(string)
    13 
    14 # bytes转字符串方式二
    15 b = b'xe9x80x86xe7x81xab'
    16 string = b.decode()  # 第一参数默认utf8,第二参数默认strict
    17 print(string)
    18 
    19 # bytes转字符串方式三
    20 b = b'xe9x80x86xe7x81hahaxab'
    21 string = b.decode('utf-8', 'ignore')  # 忽略非法字符,用strict会抛出异常
    22 print(string)
    23 
    24 # bytes转字符串方式四
    25 b = b'xe9x80x86xe7x81hahaxab'
    26 string = b.decode('utf-8', 'replace')  # 用?取代非法字符
    27 print(string)
    28 
    29 # 字符串转bytes方式一
    30 str1 = '逆火'
    31 b = bytes(str1, encoding='utf-8')
    32 print(b)
    33 
    34 # 字符串转bytes方式二
    35 b = str1.encode('utf-8')
    36 print(b)

    执行结果

    逆火
    逆火
    逆haha
    逆�haha�
    b'xe9x80x86xe7x81xab'
    b'xe9x80x86xe7x81xab'
  • 相关阅读:
    linux目录结构
    php程序员要懂那些linux知识?
    树和二叉树
    linux学习课程
    顺序栈的实现
    编写一个插件(前面JavaScript高级总结)
    javascript高级课程-4
    字符串的顺序表
    js 万年历实现
    利用 postMessage 进行数据传递 (iframe 及web worker)及问题
  • 原文地址:https://www.cnblogs.com/poloyy/p/12341746.html
Copyright © 2011-2022 走看看