1. 程式人生 > >string和bytes的關係

string和bytes的關係

為什麼要轉換?

首先,python裡面不存在位元組字串的格式化操作,即bytes是沒辦法格式化的,所以在需要將字串格式化的時候,要先轉成string。(另外說一句,如果想要位元組字串,可以先使用標準的文字字串,然後將其編碼為位元組字串)
再有就是在解析網頁的時候,會遇到獲取到的網頁(比如使用requests.content)是位元組字串,需要先轉換一下在進行解析,當然像beautifulsoup這種的會自動解析,不需要轉換。

# 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>