Python字節(jié)串"b"前綴案例解析
核心結(jié)論:前綴"b"用于創(chuàng)建字節(jié)串對象,它以二進制形式存儲數(shù)據(jù),是Python處理文件I/O、網(wǎng)絡(luò)通信等底層操作的基石。
一、基礎(chǔ)定義
官方名稱:字節(jié)串
核心功能:表示不可變的二進制數(shù)據(jù)序列(0-255的整數(shù)序列)。
語法形式:在字符串引號前加"b"或"B"
b'hello' # 字節(jié)串 b"world" # 同上 B'test' # 同上
二、數(shù)據(jù)類型特性對比
| 維度 | 普通字符串 (str) | 字節(jié)串 |
|---|---|---|
| 存儲內(nèi)容 | Unicode字符 | 原始字節(jié)數(shù)據(jù)(0-255) |
| 長度單位 | 字符數(shù) | 字節(jié)數(shù) |
| 編碼 | 已經(jīng)解碼,無需編碼 | 需要指定編碼才能轉(zhuǎn)為文本 |
| 可打印性 | 直接顯示字符 | 顯示轉(zhuǎn)義形式(如b'\xe4\xb8\xad') |
| 不可變性 | 不可變 | 不可變 |
| 類型檢查 | type('') is str | type(b'') is bytes |
本質(zhì)區(qū)別示例:
s = '中' # 長度1,包含一個Unicode字符 b = b'\xe4\xb8\xad' # 長度3,包含3個字節(jié)(UTF-8編碼) print(len(s)) # 1 print(len(b)) # 3
三、必須使用字節(jié)串的三大典型場景
1.文件I/O(二進制模式)
讀寫圖片、音頻、視頻、壓縮文件等非文本文件時,必須用字節(jié)串:
with open('image.jpg', 'rb') as f: # 注意'rb'表示二進制讀
data = f.read() # 返回bytes對象
with open('copy.jpg', 'wb') as f:
f.write(data)2.網(wǎng)絡(luò)通信(socket編程)
網(wǎng)絡(luò)協(xié)議傳輸?shù)氖窃甲止?jié)流,而非文本:
import socket
sock = socket.socket()
sock.connect(('example.com', 80))
request = b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n'
sock.sendall(request) # 必須發(fā)送bytes
response = sock.recv(4096) # 返回bytes3.加密與哈希運算
加密算法處理的是二進制數(shù)據(jù):
import hashlib md5 = hashlib.md5() md5.update(b'secret') # 必須傳入bytes print(md5.hexdigest())
四、語法規(guī)則
正確聲明方式
b'hello' # 單引號 b"world" # 雙引號 b'''multi''' # 三單引號 B"""multi""" # 三雙引號 b'\xe4\xb8\xad' # 轉(zhuǎn)義序列
常見錯誤寫法
- 混合使用編碼字符
b'中文字符' # ? SyntaxError: bytes can only contain ASCII literal b'\xe4\xb8\xad' # ? 正確:用十六進制表示UTF-8編碼
- 字符串拼接錯誤
'text' + b'bytes' # ? TypeError: can't concat str to bytes b'text' + b'bytes' # ? 正確
- 格式化不支持
b'hello {}'.format('world') # ? 字節(jié)串不支持.format()五、類型轉(zhuǎn)換方法
str → bytes(編碼)
# 方法1:encode()
text = '你好世界'
byte_data = text.encode('utf-8') # b'\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\x96\xe7\x95\x8c'
# 方法2:bytes構(gòu)造函數(shù)
byte_data = bytes(text, 'utf-8')
byte_data = bytes(text, encoding='utf-8')
# 方法3:bytes字面量(僅限ASCII)
byte_data = b'hello'bytes → str(解碼
# 方法1:decode()
text = byte_data.decode('utf-8') # '你好世界'
# 方法2:str構(gòu)造函數(shù)
text = str(byte_data, 'utf-8')
text = str(byte_data, encoding='utf-8')
# 處理解碼錯誤
text = byte_data.decode('utf-8', errors='ignore') # 忽略錯誤字符
text = byte_data.decode('utf-8', errors='replace') # 用?替換六、操作限制與替代方案
字節(jié)串不支持的字符串操作
b'hello'.upper() # ? 支持(僅ASCII)
b'hello'.lower() # ? 支持(僅ASCII)
b'hello'.strip() # ? 支持
# ? 以下操作不支持或不按預(yù)期工作:
b'hello {}'.format('world') # 不支持格式化
b'hello' + 'world' # 不能與str拼接
b'hello'.isalpha() # 非ASCII字符行為不同替代方案
- 需要高級字符串操作?先解碼
byte_data = b'hello \xe4\xb8\xad'
text = byte_data.decode('utf-8')
text = text.upper() # 使用str的方法
byte_result = text.encode('utf-8')- 字節(jié)串專用方法
b'hello'.find(b'e') # ? 支持
b'hello'.replace(b'l', b'x') # ? 支持
b'hello'.split(b'e') # ? 支持
b'abc'.hex() # ? 轉(zhuǎn)為十六進制字符串
bytes.fromhex('616263') # ? 從十六進制創(chuàng)建七、實際應(yīng)用案例
案例1:二進制文件復(fù)制器
def copy_binary_file(src, dst, chunk_size=8192):
"""高效復(fù)制二進制文件"""
with open(src, 'rb') as f_src, open(dst, 'wb') as f_dst:
while True:
chunk = f_src.read(chunk_size) # 讀取bytes塊
if not chunk:
break
f_dst.write(chunk)
# 使用示例
copy_binary_file('original.jpg', 'backup.jpg')案例2:HTTP請求客戶端
import socket
def simple_http_request(host, path='/'):
"""發(fā)送簡單的HTTP GET請求"""
# 構(gòu)建HTTP請求(必須是bytes)
request = f"GET {path} HTTP/1.1\r\nHost: {host}\r\n\r\n"
request_bytes = request.encode('utf-8')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, 80))
try:
sock.sendall(request_bytes)
response = b''
while True:
chunk = sock.recv(4096)
if not chunk:
break
response += chunk
# 分離頭部和主體
header, _, body = response.partition(b'\r\n\r\n')
print("Response Header:")
print(header.decode('utf-8', errors='ignore'))
return body
finally:
sock.close()
# 使用示例
content = simple_http_request('example.com', '/')案例3:文件哈希校驗工具
import hashlib
def calculate_file_hash(filepath, algorithm='md5'):
"""計算文件的哈希值"""
hash_func = hashlib.new(algorithm)
with open(filepath, 'rb') as f: # 二進制模式讀取
while True:
chunk = f.read(8192) # 分塊讀取bytes
if not chunk:
break
hash_func.update(chunk)
return hash_func.hexdigest()
# 使用示例
print(f"MD5: {calculate_file_hash('document.pdf', 'md5')}")
print(f"SHA256: {calculate_file_hash('document.pdf', 'sha256')}")關(guān)鍵要點總結(jié)
- 記住黃金法則:涉及二進制數(shù)據(jù)(文件/網(wǎng)絡(luò)/加密)時,用bytes;涉及文本處理時,用str
- 編碼解碼橋梁:
.encode()將 str 轉(zhuǎn)為 bytes,.decode()將 bytes 轉(zhuǎn)為 str - 錯誤處理:解碼時始終考慮
errors參數(shù)(ignore/replace) - 性能考慮:大文件操作時,分塊讀寫bytes更高效
到此這篇關(guān)于Python字節(jié)串“b“前綴案例解析的文章就介紹到這了,更多相關(guān)Python字節(jié)串“b“前綴內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用OpenCV中對圖像數(shù)據(jù)進行64F和8U轉(zhuǎn)換的方式
這篇文章主要介紹了利用OpenCV中對圖像數(shù)據(jù)進行64F和8U轉(zhuǎn)換的方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
PyCharm中Django ORM屬性提示缺失問題的解決方法
PyCharm無法識別Django模型的objects屬性提示,可能因支持未啟用、類型提示缺失或索引未更新,解決方法包括啟用Django支持、配置正確虛擬環(huán)境、添加類型注解、重建索引及更新插件,下面小編通過代碼示例給大家詳細介紹一下,需要的朋友可以參考下2025-07-07
使用Python實現(xiàn)數(shù)據(jù)庫的風(fēng)險識別
數(shù)據(jù)庫風(fēng)險發(fā)現(xiàn)系統(tǒng)旨在識別和緩解數(shù)據(jù)庫中的潛在風(fēng)險,如SQL注入,未授權(quán)訪問等,下面小編就來為大家詳細介紹一下如何使用Python實現(xiàn)數(shù)據(jù)庫的風(fēng)險識別吧2025-03-03
pycharm進行Git關(guān)聯(lián)和取消方式
這篇文章主要介紹了pycharm進行Git關(guān)聯(lián)和取消方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06

