目錄
1.相同點:bytearray與bytes取值範圍都是 0~256
2.不同點:bytearray可變的字節序列,bytes是不可變的字節序列
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')
猜你喜歡:
2.python 線程threading和進程Process區別
轉載請註明:猿說Python » python bytearray函數
技術交流、商務合作請直接聯繫博主
掃碼或搜索:猿說python
猿說python
微信公衆號 掃一掃關注