目錄
- 一.Python bytes 和 string 區別
- 二.Python string 轉 bytes
- 三. Python bytes 轉 string
- 四.猜你喜歡
基礎 Python 學習路線推薦 : Python 學習目錄 >> Python 基礎入門
一.Python bytes 和 string 區別
-
1.Python bytes 也稱位元組序列,并非字符,取值范圍 0 <= bytes <= 255,輸出的時候最前面會有字符 b 修飾;**string **是 Python 中字串型別;
-
2.bytes 主要是給在計算機看的,string 主要是給人看的;
-
3.string 經過編碼 encode ,轉化成二進制物件,給計算機識別;bytes 經過解碼 decode ,轉化成 string ,讓我們看,但是注意反編碼的編碼規則是有范圍, \xc8 就不是 utf8 識別的范圍;
!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": # 位元組物件 b
b = b"www.codersrc.com" # 字串物件 s
s = "www.codersrc.com"
print(b)
print(type(b))
print(s)
print(type(s))'''
輸出結果:b'www.codersrc.com'
<class 'bytes'>
www.codersrc.com
<class 'str'>
'''
二.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"
# 將字串轉換為位元組物件
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__":
# 位元組物件b
b = 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 for 回圈
- Python 字串
- Python 串列 list
- Python 元組 tuple
- Python 字典 dict
- Python 條件推導式
- Python 串列推導式
- Python 字典推導式
- Python 函式宣告和呼叫
- Python 不定長引數 *argc/**kargcs
- Python 匿名函式 lambda
- Python return 邏輯判斷運算式
- Python 字串/串列/元組/字典之間的相互轉換
- Python 區域變數和全域變數
- Python type 函式和 isinstance 函式區別
- Python is 和 == 區別
- Python 可變資料型別和不可變資料型別
- Python 淺拷貝和深拷貝
未經允許不得轉載:猿說編程 ? Python bytes 和 string 相互轉換
本文由博客 - 猿說編程 猿說編程 發布!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/288259.html
標籤:其他
