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,强制转换

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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内容需为不可变数据类型

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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)

你可能感兴趣的:(编程语言,python)