Python bytes string相互轉換過程解析
一.bytes和string區別
1.python bytes 也稱字節序列,并非字符。取值范圍 0 <= bytes <= 255,輸出的時候最前面會有字符b修飾;string 是python中字符串類型;
2.bytes主要是給在計算機看的,string主要是給人看的;
3.string經過編碼encode,轉化成二進制對象,給計算機識別;bytes經過解碼decode,轉化成string,讓我們看,但是注意反編碼的編碼規則是有范圍,xc8就不是utf8識別的范圍;
if __name__ == '__main__': # 字節對象b b = b'shuopython.com' # 字符串對象s s = 'shuopython.com' print(b) print(type(b)) print(s) print(type(s))
輸出結果:
b’shuopython.com’<class ’bytes’>shuopython.com<class ’str’>
二.bytes轉string
string經過編碼encode轉化成bytes
# !usr/bin/env python# -*- coding:utf-8 _*-'''@Author:何以解憂@Blog(個人博客地址): shuopython.com@WeChat Official Account(微信公眾號):猿說python@Github:www.github.com @File:python_bytes_string.py@Time:2020/2/26 21:25 @Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累!'''if __name__ == '__main__': s = 'shuopython.com' # 將字符串轉換為字節對象 b2 = bytes(s, encoding=’utf8’) # 必須制定編碼格式 # print(b2) # 字符串encode將獲得一個bytes對象 b3 = str.encode(s) b4 = s.encode() print(b3) print(type(b3)) print(b4) print(type(b4))
輸出結果:
b’shuopython.com’<class ’bytes’>b’shuopython.com’<class ’bytes’>
三.string轉bytes
bytes經過解碼decode轉化成string
if __name__ == '__main__': # 字節對象b b = b'shuopython.com' print(b) b = bytes('猿說python', encoding=’utf8’) print(b) s2 = bytes.decode(b) s3 = b.decode() print(s2) print(s3)
輸出結果:
b’shuopython.com’b’xe7x8cxbfxe8xafxb4python’猿說python猿說python
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: