python bytes string


原文链接: python bytes string

1、bytes主要是给在计算机看的,string主要是给人看的

2、中间有个桥梁就是编码规则,现在大趋势是utf8

3、bytes对象是二进制,很容易转换成16进制,例如\x64

4、string就是我们看到的内容,例如'abc'

5、string经过编码encode,转化成二进制对象,给计算机识别

6、bytes经过反编码decode,转化成string,让我们看,但是注意反编码的编码规则是有范围,\xc8就不是utf8识别的范围

7、实例:

#!/usr/bin/env python
# -*- coding: utf8 -*-
# __Author: "Skiler Hao"
# date: 2017/4/9 15:26
import hashlib

#字节对象b
b = b"example"
#字符串对象s
s = "example"
print(b)
print("example")

#将字符串转换为字节对象
b2 = bytes(s,encoding='utf8')  #必须制定编码格式
# print(b2)

#字符串encode将获得一个bytes对象
b3 = str.encode(s)
b4 = s.encode()
print(b3)
print(type(b3))
print(b4)

#将字节对象decode将获得一个str对象
s2 = bytes.decode(b)
s3 = b.decode()
print(s2)
print(s3)
# bytes转字符串方式一
b=b'\xe9\x80\x86\xe7\x81\xab'
string=str(b,'utf-8')
print(string)

# bytes转字符串方式二
b=b'\xe9\x80\x86\xe7\x81\xab'
string=b.decode() # 第一参数默认utf8,第二参数默认strict
print(string)

# bytes转字符串方式三
b=b'\xe9\x80\x86\xe7\x81haha\xab'
string=b.decode('utf-8','ignore') # 忽略非法字符,用strict会抛出异常
print(string)

# bytes转字符串方式四
b=b'\xe9\x80\x86\xe7\x81haha\xab'
string=b.decode('utf-8','replace') # 用?取代非法字符
print(string)

# 字符串转bytes方式一
str1='逆火'
b=bytes(str1, encoding='utf-8')
print(b)

# 字符串转bytes方式二
b=str1.encode('utf-8')
print(b)
复制代码
输出:

复制代码
C:\Users\horn1\Desktop\python\42-torrentParser>python convert.py
逆火
逆火
逆haha
逆�haha�
b'\xe9\x80\x86\xe7\x81\xab'
b'\xe9\x80\x86\xe7\x81\xab'

C:\Users\horn1\Desktop\python\42-torrentParser>
`