Python bytes 和 string 相互转换 - Python零基础入门教程
生活随笔
收集整理的這篇文章主要介紹了
Python bytes 和 string 相互转换 - Python零基础入门教程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
- 一.Python bytes 和 string 區(qū)別
- 二.Python string 轉 bytes
- 三. Python bytes 轉 string
- 四.猜你喜歡
基礎 Python 學習路線推薦 : Python 學習目錄 >> Python 基礎入門
一.Python bytes 和 string 區(qū)別
-
1.**Python bytes 也稱字節(jié)序列,并非字符。取值范圍 0 <= bytes <= 255,輸出的時候最前面會有字符 b 修飾;string **是 Python 中字符串類型;
-
2.bytes 主要是給在計算機看的,string 主要是給人看的;
-
3.string 經過編碼 encode ,轉化成二進制對象,給計算機識別;bytes 經過解碼 decode ,轉化成 string ,讓我們看,但是注意反編碼的編碼規(guī)則是有范圍, \xc8 就不是 utf8 識別的范圍;
二.Python string 轉 bytes
string 經過編碼 encode 轉化成 bytes,示例代碼如下:
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:猿說編程 @Blog(個人博客地址): www.codersrc.com @File:Python bytes 和 string 相互轉換.py @Time:2021/04/29 08:00 @Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累!"""if __name__ == "__main__":s = "www.codersrc.com"# 將字符串轉換為字節(jié)對象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'www.codersrc.com' <class 'bytes'> b'www.codersrc.com' <class 'bytes'>'''三. Python bytes 轉 string
bytes 經過解碼 decode 轉化成 string ,示例代碼如下:
if __name__ == "__main__":# 字節(jié)對象bb = b"www.codersrc.com"print(b)b = bytes("猿說python", encoding='utf8')print(b)s2 = bytes.decode(b)s3 = b.decode()print(s2)print(s3)''' 輸出結果:b'www.codersrc.com' b'\xe7\x8c\xbf\xe8\xaf\xb4python' 猿說python 猿說python '''四.猜你喜歡
未經允許不得轉載:猿說編程 ? Python bytes 和 string 相互轉換
總結
以上是生活随笔為你收集整理的Python bytes 和 string 相互转换 - Python零基础入门教程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言 数组排序 – 快速法排序 - C
- 下一篇: websocket python爬虫_p