Python bytes型別及用法詳解

2022-06-05 12:42:08 字數 1044 閱讀 1129

python bytes 型別用來表示乙個位元組串。「位元組串「不是程式設計術語,是我自己「捏造」的乙個詞,用來和字串相呼應。

bytes 是 python 3.x 新增的型別,在 python 2.x 中是不存在的。

位元組串(bytes)和字串(string)的對比:

【例項】使用不同方式建立 bytes 物件:

#

通過建構函式建立空 bytes

b1 =bytes()

#通過空字串建立空 bytes

b2 = b''

#通過b字首將字串轉換成 bytes

b3 = b'

'print("

b3:

", b3)

print(b3[3])

print(b3[7:22])

#為 bytes() 方法指定字符集

b4 = bytes('

python資料

', encoding='

utf-8')

print("

b4:

", b4)

#通過 encode() 方法將字串轉換成 bytes

b5 = "p

ython資料

".encode('

utf-8')

print("

b5:

", b5)

對於非 ascii 字元,print 輸出的是它的字元編碼值(十六進製制形式),而不是字元本身。非 ascii 字元一般占用兩個位元組以上的記憶體,而 bytes 是按照單個位元組來處理資料的,所以不能一次處理多個位元組。

bytes 類也有乙個 decode() 方法,通過該方法可以將 bytes 物件轉換為字串。緊接上面的程式,新增以下**:

#

通過 decode() 方法將 bytes 轉換成字串

str1 = b5.decode('

utf-8')

print("

str1:

", str1)

汗的型別及基礎用方

汗出惡寒脈浮 桂枝湯 常自汗出 桂枝湯 時汗出 桂枝湯並先其服用喝水出汗 漏汗 桂枝加附子 陽明病發多汗 白虎湯 續自汗出身無大熱切喘 麻杏石甘湯 手足濈然汗出 大便實故也 汗出 項背強嘰嘰 桂枝加葛根湯 惡寒 項背強幾幾 葛根湯 頭汗出齊頸而還 有溼 自汗 玉屏風散 牡蠣散 多汗容易感冒 桂枝加黃...

如何判斷int型別大小及sizeof的用法

sizeof 不是函式,是運算子的同時還是關鍵字。功能 求解乙個變數 一種型別它佔多少位元組。1gb 1024 mb 210 mb 1mb 1024 kb 210 kb 1kb 1024 b 210 b 1b 8bit 整數 long long 四字 int dword 雙字 short word ...

named struct型別怎麼用

今天用到了named struct型別,主要用這個函式做json拼接 select named struct supplier sku id supplier sku id,supplier id t1.supplier id,prefee rate prefee rate,order rate o...