八、数据类型转换
整形 int
number = 100
字符串 str
name = 'Yangyang'
列表 list
name_list = ['Yangyang', 'Lindy', 'Alice', 'Leimei', 'Jack']
元组 tuple
name_tuple = ('Yangyang', 'Lindy', 'Alice', 'Leimei', 'Jack')
字典 dict
study = {"bdc":30, "listen":5, "read":2}
image
【字符串】转【整形】
int('25')
# 输出:
# 25
【整形】转【字符串】
str(3820594)
# 输出:
# '3820594'
【字符串】转【列表】
(数字不能直接转列表)
list('3820594')
# 输出:
# ['3', '8', '2', '0', '5', '9', '4']
【列表】转【元组】
tuple(list('3820594'))
# 输出:
# ('3', '8', '2', '0', '5', '9', '4')
【元组】转【列表】
list(tuple('3820594'))
# 输出:
# ['3', '8', '2', '0', '5', '9', '4']
【元组】转【字符串】
number = ('3', '8', '2', '0', '5', '9', '4')
"".join(number)
# 输出:
# '3820594'
【列表】转【字符串】
number = ['3', '8', '2', '0', '5', '9', '4']
"".join(number)
# 输出:
# '3820594'
【字典】转【列表】,只有key,没有value
study = {'bdc': 30, 'listen': 5, 'read': 2, 'sentence': 10}
print(list(study))
# 输出:
# ['bdc', 'listen', 'read', 'sentence']
【两个列表】转【字典】
name = ["bdc", "listen", "read", "sentence"]
number = [30, 5, 2, 10]
study = {key:value for key,value in zip(name, number)}
print(study)
# 输出:
# {'bdc': 30, 'listen': 5, 'read': 2, 'sentence': 10}
网友评论