您的位置:首页 > 编程语言 > Python开发

python 字符串 元组 列表 字典 间的相互转化

2017-02-06 13:49 555 查看
# -*- coding: utf-8 -*-

if __name__ == '__main__':
# 1、字典
dict = {'Name' :'Jack', 'Age':20, 'Gender':'Male'}
print '字典转换为字符串:', type(str(dict)), str(dict)
print '字典转换为元组:', tuple(dict), tuple(dict.values())
print '字典转换为列表:', list(dict), dict.values()

# 2、元组  注:元组不可转换为字典
tup = (1, 3, 5, 7, 9)
print '元组转换为字符串:', tup.__str__()
print '元组转换为列表:', list(tup)

# 3、列表  注:列表不可转换为字典
nums = [2, 4, 6, 8, 10, 12, 14]
print '列表转换为字符串:', str(nums)
print '列表转换为元组:', tuple(nums)

# 4、字符串
print '字符串转换为元组:', tuple(eval("(1,2,3)"))
print '字符串转换为列表:', list(eval("(1,2,3)"))
print '字符串转换为字典:', type(eval("{'Name' :'Json', 'Age':22}")), eval("{'Name' :'Json', 'Age':22}")

# 字符串与字典的区别  (temp1是字典 temp2是字符串  只是相差一个双引号)
temp1 = {'Name' :'Jack', 'Age':20, 'Gender':'Male'}
temp2 = "{'Name' :'Jack', 'Age':20, 'Gender':'Male'}"
print type(temp1), type(temp2)


输出结果:

字典转换为字符串: <type 'str'> {'Gender': 'Male', 'Age': 20, 'Name': 'Jack'}
字典转换为元组: ('Gender', 'Age', 'Name') ('Male', 20, 'Jack')
字典转换为列表: ['Gender', 'Age', 'Name'] ['Male', 20, 'Jack']
元组转换为字符串: (1, 3, 5, 7, 9)
元组转换为列表: [1, 3, 5, 7, 9]
列表转换为字符串: [2, 4, 6, 8, 10, 12, 14]
列表转换为元组: (2, 4, 6, 8, 10, 12, 14)
字符串转换为元组: (1, 2, 3)
字符串转换为列表: [1, 2, 3]
字符串转换为字典: <type 'dict'> {'Age': 22, 'Name': 'Json'}
<type 'dict'> <type 'str'>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: