網站首頁 編程語言 正文
Bytes和Str的區別
在Python3中,字符序列有兩種類型:bytes和str。bytes類型是無符號的8位值(通常以ASCII碼顯式),而str類型是Unicode代碼點(code point)。代碼點指編碼字符集中,字符所對應的數字。
a = b'hello world'
print(isinstance(a, bytes))
print(list(a))
print(a)
"""
True
[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
b'hello world'
"""
a = 'hello world'
print(isinstance(a, str))
print(list(a))
print(a)
"""
True
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
hello world
"""
isinstance()方法可以判斷對象的類型,例如這里用來判斷是str還是bytes。
Python3對文本(str)和二進制數據(bytes)有著嚴格的區分,不能混用。
x = b'python'
y = b'java'
z = 'c++'
w = 'c'
print(x + y)
# b'pythonjava'
print(z + w)
# c++c
print(x + z)
# TypeError: can't concat str to bytes
print('python' == b'python')
# False
上述示例中str類型和bytes類型間使用=來比較是否相等不會報錯,但是會返回False。
Bytes與Str間的轉換
str類型和bytes類型間可以相互轉換。
str到bytes的轉換需要調用encode()方法。
bytes到str間的轉換需要調用decode()方法。
x = b'python'
y = x.decode(encoding='utf-8')
z = y.encode(encoding='utf-8')
print(y)
print(z)
"""
python
b'python'
"""
可以觀察到encode()和decode()方法都有一個encoding參數用來指定具體的編碼規則。
讀寫文件的注意事項
當要將bytes類型寫入到文件中時,必須指定mode=wb。讀取二進制文件時可以指定mode=rb或者指定編碼方式,使用后者時讀出來的就不是bytes類型的字符序列了。
x = b'python'
# 錯誤示例
with open('data.bin', mode='w') as fp:
fp.write(x)
# TypeError: write() argument must be str, not bytes
# 正確示例
with open('data.bin', mode='wb') as fp:
fp.write(x)
# 讀取二進制文件方式1
with open('data.bin', mode='rb') as fp:
content = fp.read()
print(content)
# python
# 讀取二進制文件方式2
with open('data.bin', mode='r', encoding='utf-8') as fp:
content = fp.read()
print(content, type(content))
# python <class 'str'>
當讀寫Unicode數據時,只需要注意下編碼方式即可,最好是顯式的傳遞encoding參數。
x = '世界你好'
with open('data.txt', mode='w', encoding='utf-8') as fp:
fp.write(x)
with open('data.txt', mode='r', encoding='utf-8') as fp:
content = fp.read()
print(content)
# 世界你好
# 錯誤示例,編碼方式不對
with open('data.txt', mode='r', encoding='gbk') as fp:
content = fp.read()
print(content)
# 涓栫晫浣犲ソ
總結
原文鏈接:https://blog.csdn.net/qq_42103091/article/details/124573589
相關推薦
- 2023-07-09 前端axios請求,傳遞數組的時候會在url的后邊加中括號[]
- 2021-12-13 一次現網問題定位-Redis連接不斷增長
- 2023-02-12 Golang中反射的常見用法分享_Golang
- 2022-08-01 如何利用python將Xmind用例轉為Excel用例_python
- 2022-04-11 用C++實現SLR語法分析程序_C 語言
- 2023-02-02 C語言中的冒泡排序問題_C 語言
- 2022-02-19 數據結構C語言鏈表的實現介紹_C 語言
- 2022-04-07 你知道怎么基于?React?封裝一個組件嗎_React
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支