各种数据类型相互转换

将类似‘id=3,name=abc’字符串转为[['id', '3'], ['name', 'abc']]

str = 'id=3,name=abc'
column_name = str.split(',')
column_name = [i for i in column_name if i!='']                   # 列表去空 可不写
l = [el.split('=') for el in lst if '=' in el]
print(l)               #==>[['id', '3'], ['name', 'abc']]

int转换成其他类型

int -->str           str(int)  可以直接任意转换

int -->bool        非0为真

int -->tuple       不能这么做 报错

int -->list           不能这么做 报错  int不是可迭代的 

int-->dict           不能这么做 报错

int-->set           不能转

tuple转换成其他类型

tuple-->str            会连同括号等全部作为字符串      str((1, 'e', [1, '3'], {1: 'qq'})) ==> “(1, 'e', [1, '3'], {1: 'qq'})”  但是这个类型是字符串其中的''单引号也算在字符串内

tuple-->bool        非空为True

tuple-->int            只有str类型才能转成int, 在str全部为数字的情况下否则报错

tuple-->list           元组内的数据类型不变,完美转换为列表

tuple-->dict          不能这么做 报错

list转换成其他类型

list-->str               str([1, '2', [1, 2], {1: 'www'}])  ==> ''[1, '2', [1, 2], {1: 'www'}]" 将方括号与数据原样作为字符串输出   其中的''单引号也算在字符串内

list-->bool            非空为True

list-->int                只有str类型才能转成int, 在str全部为数字的情况下否则报错

list-->tuple            完美转换,原list内的数据类型不改变

list-->dict              不能这么做 报错

list-->set                列表去重插入集合中

str字符串转换成其他类型

str-->tuple            将字符串迭代插入元组     tuple('qweasd') ==> ('q', 'w', 'e', 'a', 's', 'd')  

str-->list               迭代插入列表         list('qweasd') ==> ['q', 'w', 'e', 'a', 's', 'd'] 

str-->dict              不能这么做 报错

str-->bool             非空为True

str-->int                全字数字可以,如果有非数字将报错

str-->set                迭代插入集合,b并去重。 set('qweasdddd') ==> {'q', 'w', 'e', 'a', 's', 'd'} 

dict转换成其他类型

dict-->str                    str({'q' ,'1'}) ==>"{'q' ,'1'}"    包括括号原样输出为字符串其中的''单引号也算在字符串内

dict-->bool                  非空为True

dict-->int                     只有str类型才能转成int, 在str全部为数字的情况下否则报错

dict-->tuple                 只将字典的key放到元组中,字典的key类型不变,如果只有一个元素要只有一个逗号    例:(a,)

dict-->list                    list(dict)   [key, key.....]强转后  列表中只会存在字典的所有key.

bool转换成其他类型

str   -->bool                非空为True

dict-->bool                非空为True

int   -->bool                非0为True

tuple-->bool              非空为True

list   -->bool               非空为True

原文地址:https://www.cnblogs.com/Mr-wangxd/p/9402674.html