python基础之数据类型转换

方法转换:str -->list str.split()    list -->str ''.join(list)
强制转换:str -->list list(str) str -->tuple tuple(str) str -->set set(str)
list -->tuple tuple(list) list -->set set(list)
tuple -->list list(tuple) tuple -->set set(tuple)
set -->list list(set) set -->tuple tuple(set)
str,tuple,list,dict,set -->bool bool(obj)

1,str --> list split
ey:
str1 = 'a b c d'
list1 = str1.split()
print(list1)
result:['a', 'b', 'c', 'd']
ey:
str1 = 'a,b,c,d'
list1 = str1.split(',')
print(list1)
result:['a', 'b', 'c', 'd']
ey:
str1 = 'abcd'
list1 = str1.split('c')
print(list1)
result:['ab', 'd']
2,list --> str join
ey:
list2 = ['1','2','3','dd']
str2 = '*'.join(list2)
print(str2)
result:1*2*3*dd
3,强制转换
str --> list
ey:
str1 = 'abcd'
list1 = list(str1)
print(list1)
result:['a', 'b', 'c', 'd']
4,str -->tuple
s1 = '123wwrw'
print(tuple(s1))
result:('1', '2', '3', 'w', 'w', 'r', 'w')
5,str -->set
s1 = '123wwrw'
print(set(s1))
result:{'1', 'w', 'r', '3', '2'}
6,空的str list tuple dict set 转换为bool 为false ,非空为true
7,list --> set 达到去重效果,list内容需为不可变数据类型
l1 = [1,2,31,1,2]
set1 = set(l1)
print(set1)
result:{1, 2, 31}
ey:
l1 = [1,2,31,1,2,[12,33]]
tu2 = set(l1)
print(tu2)
result:TypeError: unhashable type: 'list'
8,set -->list
set1 = set({1,2,3})
l1 = list(set1)
print(l1)
result:[1, 2, 3]
9,list -->tuple
l1 = [1,2,31,1,2]
tu1 = tuple(l1)
print(tu1)
result:(1, 2, 31, 1, 2)
10,tuple -->list
tu1 = (1,2,3)
l2 = list(tu1)
print(l2)
result:[1, 2, 3]
11, tuple -->set
tu1 = (1,2,3)
set2 = set(tu1)
print(set2)
result:{1, 2, 3}
12,set -->tuple
set1 = set({1,2,3})
tu1 = tuple(set1)
print(tu1)

result:(1, 2, 3)
posted @ 2019-08-22 17:56  joker_you  阅读(284)  评论(0编辑  收藏  举报