1. 程式人生 > >python 學習彙總48:資料型別相互轉換(基礎學習- 推薦 tcy)

python 學習彙總48:資料型別相互轉換(基礎學習- 推薦 tcy)

 型別轉換 2018/9/12
1.轉換函式


str(x) 將物件x轉換為字串
str(bytes_or_buffer[, encoding[, errors]])
repr(x) 將物件x轉換為表示式字串
eval(str) 計算字串中表達式的值
ascii() 返回一個可列印物件字串;非ASCII碼輸出\x,\u
format(x,[,format_spec])將物件x轉格式化字串

bytes(ints=) #整形數字0-255
bytes(length: int)
bytes(str,encoding=,errors)
bytearray([source, encoding , errors])

tuple(s) 將s(可迭代)轉元組
list(s) 將s(可迭代)轉列表
dict(k,v) 將(k,v)轉dict
set(s) 將s(可迭代)轉集合
array('i',s) 將s(可迭代)轉陣列
chr(int x) 將一個整數轉換為一個字元
ord(str x) 將一個字元轉換為它的整數值
bool([x]) 字元轉換為Boolean型別
*****************************************************************
bin(s) 整數轉2進位制字串
oct(x) 整數轉8進位制字串
hex(x) 整數轉16進位制字串

int(x[, base]) 將x轉換為一個整數 x 數值或字串
long(x[, base]) 將x轉換為一個長整數
float(x) 將x轉換到一個浮點數
complex(real[, imag]) 建立一個複數 
str.encode(encoding='utf-8') 字串編碼生成bytes
bytes.decode('utf-8') 位元組解碼生成str 
bytes().fromhex('010210') 16進位制字串轉位元組 b'\x01\x02\x10'
binascii.b2a_hex(b'\x01\x02\x10') 位元組轉16進位制字str b'010210'
struct.pack(fmt,buffer ) 把任意資料型別變成bytes
struct.unpack(fmt, string) 將bytes轉換成python資料型別
2.例項 :  
2.1.str轉number,bytes

# Unicode str轉int
ord('a') #97 【chr(97) #'a'】
ord('特') # 29305 【chr(29305) #'特'】

# str轉int:2,8,10,16進位制str要和後面的base對應
int('-0b10000',2) #-16 【bin(-16) #'-0b10000'】
int('0o20',8) #16 【oct(16) #'0o20'】
int('16',10) #16 【str(16) #'16'】
int('0x10',16) #16 【hex(16) #'0x10'】

# str轉bytes
b1='0b10000'.encode() #b'0b10000'【b1.decode() #'0b10000'】
b2='0o20'.encode() #b'0o20' 【b1.decode() #'0o20'】
b3='16'.encode() #b'16' 【b1.decode() #'16】
b4='0x10'.encode() #b'0x10' 【b1.decode() #'0x10'】

'12abc'.encode('ascii') == > b'12abc'

# str轉bytes--整數陣列
b1=bytes([ord('T'),ord('e'),ord('s'),ord('t')])#b'Test'
b1=bytes([84, 101, 115, 116]) #b'Test'
b1=bytes([0x54,0x65,0x73,0x74]) #b'Test'

b1=bytes().fromhex('54657374') #16進位制字元 #b'Test'
b1=bytes(map(ord, '\x54\x65\x73\x74')) #b'Test' 【b1.decode() #'Test'】

# str求值
eval('3,4,5') #將字串求值(3, 4, 5)

#str轉ascii
ascii('test-1 中國 \\n') #"'test-1 \\u4e2d\\u56fd \\\\n'"
ascii('b\31') # 'b\x19'
ascii('0x\1000') #'
[email protected]
' ------------------------------------------------------------------------------ 2.2.bytes轉number,str,bytes # bytes轉int:(str進位制和base進位制相同) int(b'0b10000',2) #16【不能轉換,要用struct.pack,unpack】 int(b'0o20',8) #16 int(b'16',10) #16 int(b'0x10',16) #16 # bytes轉str b1.decode() # '中國' 【b1='中國'.encode() # b'\xe4\xb8\xad\xe5\x9b\xbd'】 b1.decode() # 'Test'【b1=bytes([0x54,0x65,0x73,0x74]).decode('ascii')# 'Test'】 str(bytes(b'Test'))[2:-1] # 'Test' # 16bytes轉16bytes b1 = binascii.b2a_hex(b'\x54\x65\x73\x74');#b'54657374' # b2 = binascii.b2a_hex(b'54657374') #b'3534363537333734' c1 = binascii.a2b_hex(b1) #b'Test' # c2 = binascii.a2b_hex(b2) #b'54657374' # bytes轉16進位制str陣列: [hex(x) for x in bytes(b'\x54\x65\x73\x74\x2d\x31')] # ['0x54', '0x65', '0x73', '0x74', '0x2d', '0x31'] ------------------------------------------------------------------------------ 2.3.數字轉換 # int轉Unicode str: chr(97) # 'a' 【ord('a') #97】 chr(29305) # '特' 【ord('特') #29305】 # int轉str:2,8,10,16進位制 b1=bin(-16) # '-0b10000'【int(b1,2) #-16】 b2=oct(0b10000) # '0o20' 【int(b2,8) #16】 b3=str(0x10) # '16' 【int(b3,10) #16】 b4=hex(0o20) # '0x10' 【int(b4,16) #16】 # 整數轉位元組 # 不能轉換,必須通過str做橋樑:int-->str-->bytes
3.python基本資料型別<-->types:
# int-->bytes
struct.pack('<HH', 1, 2) == > b'\x01\x00\x02\x00' #轉為兩個位元組
struct.pack('<LL', 1, 2) == > b'\x01\x00\x00\x00\x02\x00\x00\x00' #轉為四個位元組

# bytes-->int
struct.unpack('<hh', bytes(b'\x01\x00\x00\x00')) == > (1, 0) #轉short int
struct.unpack('<L', bytes(b'\x01\x00\x00\x00')) == > (1,) #轉long int
4.資料型別轉換:
bool([x]) 字元轉換為Boolean型別
# 說明:
# 以下值被認為是False:
# 0,0.0;空字串'',"";None;空集合(),[],{};
# 在if、while等條件判斷語句:if bool(a)等同於if a != ''

# 例項:
bool() #False
bool('') # False
bool(' ') # True
bool({}) # False
bool(()) # False
bool([]) # False
bool(None) # False
bool(0) # False
bool(0.0) # False
bool('False') # True

a1=int(3.14) #3
float(3) #3.0
float('3.14') #3.14
a=1 + 2j #(1 + 2j)
complex(a) #(1 + 2j)
5.序列轉換
	str,tuple,list,dict,set,array轉換:
5.1.函式
# str tuple,list ,dict,set,frozenset,array都是可迭代

str(object=b'', encoding='utf-8', errors='strict')
tuple([iterable]) #序列和可迭代物件轉list,元素排序不變
list([iterable]) #序列和可迭代物件轉list,元素排序不變

dict(mapping)
dict(iterable)
dict(**kwargs)

set([ iterable ] )
frozenset([ iterable ] ) 
5.2.例項: 
import array as array
str0 = "abc123"


1) .str轉其他型別

a1=tuple(str0) # ('a', 'b', 'c', '1', '2', '3')
a1=list(str0) # ['a', 'b', 'c', '1', '2', '3']
d1 = dict(zip(str0, str0)) #{'a':'1','b':'2','c':'3'}

k1 = str0[0:3];v1 = str0[3:]
d1 = dict(map(lambda k1, v1: (k1, v1), k1, v1))# {'a': '1', 'b': '2', 'c': '3'}

d2 = dict.fromkeys(str0, 0) #{'a':0,'b':0,'c':0}
s1=set(str0) #{'2', '1', 'b', '3', 'c', 'a'}
a1=array.array('u',str0) #array('u', 'abc123')
------------------------------------------------------------------------------------
2) .其他型別轉str

(1)標準str型別 如"abc123"
str1="".join(t1) #t1全是char
str1=''.join([str(i) for i in t1])

(2)其他類外加分號 如"(1,2,3,'test')"
t=(1,2,3,'test')
b=eval(str(tuple(t))) #tuple可為其他5種類型

------------------------------------------------------------------------------------

3).tuple轉換

t=(1,2,3.1)

a=list(t) # [1, 2, 3.1]
a=dict(zip(t,t)) # {1: 1, 2: 2, 3.1: 3.1}
a=set(t) # {1, 2, 3.1}
a=array('f',t) # array('f', [1.0, 2.0, 3.0999999046325684])

-------------------------------------------------------------------------------------
4).list轉換
lst=(1,2,3.1)

a=tuple(lst) # (1, 2, 3.1)
a=dict(zip(lst,lst)) # {1: 1, 2: 2, 3.1: 3.1}
a=set(lst) # {1, 2, 3.1}
a=array.array('f',lst) # array('f', [1.0, 2.0, 3.0999999046325684])
--------------------------------------------------------------------------------------
5).dict轉換
d={'k1':11,'k2':22,'k3':33}

a1=tuple(d) # ('k1', 'k2', 'k3')
a2=tuple(d.items()) # (('k1', 11), ('k2', 22), ('k3', 33))
a3=tuple(d.keys()) # ('k1', 'k2', 'k3')
a4=tuple(d.values()) # (11, 22, 33)

a1=list(d) # ['k1', 'k2', 'k3']
a2=list(d.items()) # [('k1', 11), ('k2', 22), ('k3', 33)]
a3=list(d.keys()) # ['k1', 'k2', 'k3']
a4=list(d.values()) # [11, 22, 33]

a1=set(d) # {'k1', 'k2', 'k3'}
a2=set(d.items()) # {('k3', 33), ('k1', 11), ('k2', 22)}
a3=set(d.keys()) # {'k1', 'k2', 'k3'}
a4=set(d.values()) # {33, 11, 22}

a1=array('u',str(d)) # array('u', "{'k1': 11, 'k2': 22, 'k3': 33}")
a2=array('u',str(d.items())) # array('u', "dict_items([('k1', 11), ('k2', 22), ('k3', 33)])")
a3=array('u',str(d.keys())) # array('u', "dict_keys(['k1', 'k2', 'k3'])")
a4=array('f',d.values()) # array('f', [11.0, 22.0, 33.0])
--------------------------------------------------------------------------------------
6).set轉換
s={1,2,3}

a=tuple(s) # (1, 2, 3)
a=list(a) # [1, 2, 3]
a=dict(zip(s,s)) # {1: 1, 2: 2, 3: 3}
--------------------------------------------------------------------------------------
7).array轉換
s=array.array('i',[1,2,3])

a=tuple(s) # (1, 2, 3)
a=list(s) # [1, 2, 3]
a=dict(zip(s,s)) # {1: 1, 2: 2, 3: 3}
a=set(s) # {1, 2, 3}