一.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'\xe7\x8c\xbf\xe8\xaf\xb4python' 猿說python 猿說python
猜你喜歡:
1.python bytes
2.python bytearray
3.python 深拷貝和淺拷貝
4.python 區域變數和全域變數
轉載請注明:猿說Python ? python bytes和string相互轉換
技術交流、商務合作請直接聯系博主 掃碼或搜索:猿說python
猿說python
微信公眾號 掃一掃關注
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/184114.html
標籤:Python
