python除了 bytes位元組序列 之外,還有bytearray可變的位元組序列,具體區別在哪呢?顧名思義,前者是不可變的,而后者是可變的!具體本文會有詳細的講解!
一.bytearray函式簡介
# 1.定義空的位元組序列bytearray bytearray() -> empty bytearrayarray # 2.定義指定個數的位元組序列bytes,默認以0填充,不能是浮點數 bytearray(int) -> bytes array of size given by the parameter initialized with null bytes # 3.定義指定內容的位元組序列bytes bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer # 4.定義指定內容的位元組序列bytes bytearray(string, encoding[, errors]) -> bytearray # 5.定義指定內容的位元組序列bytes,只能為int 型別,不能含有float 或者 str等其他型別變數 bytearray(iterable_of_ints) -> bytearray
回傳值:回傳一個新的可變位元組序列,可變位元組序列bytearray有一個明顯的特征,輸出的時候最前面會有一個字符b標識,舉個例子:
b'\x64\x65\x66' b'i love you' b'shuopython.com'
凡是輸出前面帶有字符b標識的都是位元組序列bytes;
二.bytearray函式使用
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:何以解憂 @Blog(個人博客地址): shuopython.com @WeChat Official Account(微信公眾號):猿說python @Github:www.github.com @File:python_bytearray.py @Time:2020/2/26 21:25 @Motto:不積跬步無以至千里,不積小流無以成江海,程式人生的精彩需要堅持不懈地積累! """ if __name__ == "__main__": # 定義空的位元組序列bytearray b1 = bytearray() print(b1) print(type(b1)) print("***"*20) # 定義指定個數的位元組序列bytes,默認以0填充,不能是浮點數 b2 = bytearray(10) print(b2) print(type(b2)) print("***" * 20) # 定義指定內容的位元組序列bytes b3 = bytes('abc', 'utf-8') print(b3) print(type(b3)) print("***" * 20) # 正常輸出 b1 = bytearray([1, 2, 3, 4]) >> > b'\x01\x02\x03\x04' # bytes位元組序列必須是 0 ~ 255 之間的整數,不能含有float型別 b1 = bytearray([1.1, 2.2, 3, 4]) >> > TypeError: an integer is required # bytes位元組序列必須是 0 ~ 255 之間的整數,不能含有str型別 b1 = bytearray([1, 'a', 2, 3]) >> > TypeError: an integer is required # bytes位元組序列必須是 0 ~ 255 之間的整數,不能大于或者等于256 b1 = bytearray([1, 257]) >> > ValueError: bytes must be in range(0, 256)
輸出結果:
bytearray(b'') <class 'bytearray'> ************************************************************ bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') <class 'bytearray'> ************************************************************ b'abc' <class 'bytes'> ************************************************************
三.bytearray與bytes區別
1.相同點:bytearray與bytes取值范圍都是 0~256
2.不同點:bytearray可變的位元組序列,bytes是不可變的位元組序列
A. bytes不可變位元組序列
if __name__ == "__main__": # bytes不可變位元組序列 b1 = b"abcd" for i in b1: print(i,end=" ") print() b1[0] = "A"
輸出結果:
97 98 99 100 Traceback (most recent call last): File "E:/Project/python/python_project/untitled10/123.py", line 22, in <module> b1[0] = "A" TypeError: 'bytes' object does not support item assignment
B.bytearray可變位元組序列
if __name__ == "__main__": # bytearray可變位元組序列 b1 = b"abcd" b2 = bytearray(b1) print("修改之前:",b2) b2[0] = 65 print("修改之后:", b2)
輸出結果:
修改之前: bytearray(b'abcd') 修改之后: bytearray(b'Abcd')
猜你喜歡:
1.python bytes函式
2.python 執行緒threading和行程Process區別
3.python GIL鎖
4.python GIL鎖與互斥鎖區別
轉載請注明:猿說Python ? python bytearray函式
技術交流、商務合作請直接聯系博主 掃碼或搜索:猿說python
猿說python
微信公眾號 掃一掃關注
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/185249.html
標籤:Python
