本文主要是介绍python 基本数据类型bool,int,float,str,bytes,tuple,list,set,array相互转换(汇总 全面)tcy,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
类型转换 2018/9/12 汇总网上资料,修改新增实例;内容比较详详细。 ------------------------------------------------------------------------------ 1.转换函数*****************************************************************str(x) 将对象x转换为字符串str(bytes_or_buffer[, encoding[, errors]])repr(x) 将对象x转换为表达式字符串eval(str) 计算字符串中表达式的值ascii() 返回一个可打印对象字符串;非ASCII码输出\x,\uformat(x,[,format_spec])将对象x转格式化字符串*****************************************************************bytes(ints=) #整形数字0-255bytes(length: int)bytes(str,encoding=,errors)bytearray([source, encoding , errors])*****************************************************************tuple(s) 将s(可迭代)转元组list(s) 将s(可迭代)转列表dict(k,v) 将(k,v)转dictset(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') 字符串编码生成bytesbytes.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 ) 把任意数据类型变成bytesstruct.unpack(fmt, string) 将bytes转换成python数据类型*****************************************************************------------------------------------------------------------------------------- 2.实例2.1.str转number,bytes# Unicode str转intord('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转bytesb1='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转asciiascii('test-1 中国 \\n') #"'test-1 \\u4e2d\\u56fd \\\\n'"ascii('b\31') # 'b\x19'ascii('0x\1000') #'0x@0'------------------------------------------------------------------------------2.2.bytes转number,str,bytes# bytes转int:(str进制和base进制相同)int(b'0b10000',2) #16【不能转换,要用struct.pack,unpack】int(b'0o20',8) #16int(b'16',10) #16int(b'0x10',16) #16# bytes转strb1.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转16bytesb1 = 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-->bytesstruct.pack('<HH', 1, 2) == > b'\x01\x00\x02\x00' #转为两个字节struct.pack('<LL', 1, 2) == > b'\x01\x00\x00\x00\x02\x00\x00\x00 #转为四个字节# bytes-->intstruct.unpack('<hh', bytes(b'\x01\x00\x00\x00')) == > (1, 0) #转short intstruct.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() #Falsebool('') # Falsebool(' ') # Truebool({}) # Falsebool(()) # Falsebool([]) # Falsebool(None) # Falsebool(0) # Falsebool(0.0) # Falsebool('False') # Truea1=int(3.14) #3float(3) #3.0float('3.14') #3.14a=1 + 2j #(1 + 2j)complex(a) #(1 + 2j)5.序列转换
str,tuple,list,dict,set,array转换---------------------------------------------------------------------------------- 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 ] ) ----------------------------------------------------------------------------------- 2.实例import array as arraystr0 = "abc123"-----------------------------------------------------------------------------------2.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.2.其他类型转str1)标准str类型 如"abc123"str1="".join(t1) #t1全是charstr1=''.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.1.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.1.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.1.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.1.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.1.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}--------------------------------------------------------------------------------------
这篇关于python 基本数据类型bool,int,float,str,bytes,tuple,list,set,array相互转换(汇总 全面)tcy的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!