PY3 內建資料結構 5 字串編碼

2022-07-03 20:33:11 字數 1934 閱讀 3314

python2中只有 unicode型別

而python3中有 string bytes兩種型別 

1.str是文字序列、bytes是位元組序列 (文字=字元)

2.位元組是沒有編碼的、文字是有編碼的(單位元組編碼/雙位元組編碼):utf-8 gbk,gb18030等

3.什麼是編碼?

編碼可以說是一種「位元組的組織方式」

字元是由位元組組成的,而字元的編碼規定了它是如何來組織這些位元組的,即如何使用位元組來表示這些字元

#

encode()用於將str ——> bytes

in [1]: '盧'

.encode()

out[1]: b'

\xe5\x8d\xa2

'in [2]: bin(0xe5)

out[2]: '

0b11100101

'in [3]: bin(0x8d)

out[3]: '

0b10001101

'in [4]: bin(0xa2)

out[4]: '

0b10100010

' //所以'盧'

在計算機中的表示就是這些二進位制

#python3字串預設使用utf-8編碼,encode('')可指定不同編碼方式

in [5]: '

盧'.encode('

gbk'

)out[5]: b'

\xc2\xac'#

decode()用於將bytes ——> str

in [6]: b'

\xe5\x8d\xa2

'.decode()

out[6]: '

盧'

#

通過b字首(b' ')定義bytes

#除了encode外,str的操作都有對應bytes的版本, 但是傳入引數也必須是bytes

in [1]: b'

abc'.find('b'

)typeerror: a bytes-like object is required, not

'str

'in [2]: b'

abc'.find(b'b'

)out[2]: 1

#要注意bytes的操作是按照位元組來的

in [3]: len('盧'

.encode())

in [3]: 3in [4]: '

盧'.encode().find(b'

\xe5')

out[4]: 0

#bytes型別自身的兩個操作:decode()、hex()

in [6]: b.decode()

out[6]: '

abc'

in [7]: b.hex() //轉化為16進製制

out[7]: '

616263

'

# 

bytearray是bytes的可變版本

# #

# 並且可以索引操作

# in [11]: b=b'

abc'

;type(b)

out[11]: bytes

in [13]: ba=bytearray(b);type(ba)

out[13]: bytearray

in [15]: b[1]=b'b'

typeerror:

'bytes

' object does not

support item assignment

in [16]: ba[1]=int(b'

b'.hex(),16); print

(ba)

out[16]:bytearray(b'

abc')

資料結構3 字串

string的基本操作函式要會,拷貝,查詢 hw筆試第一題,兩個字串,前面是全量字符集,後面是已占用字符集 用 隔開 輸出剩餘的字符集。1 include2 include3 using namespace std 4string stringoperate string str1,string s...

PY3 內建資料結構 8 解構與封裝

解構的理解與用法 解構是python很有特色的乙個功能,被很多語言借鑑 例如es6 元素按照順序賦值給變數in 31 lst list range 5 in 32 head,mid,tail lst in 33 print head,tail 0 4in 34 print mid 1,2,3 變數和...

資料結構 5 字串 C語言

define maxsize 40 儲存空間初始分配量 typedef int status status是函式的型別,其值是函式結果狀態 如ok等 typedef int elemtype elemtype型別根據實際情況而定,這裡假設為int typedef char string maxsiz...