首页 > 其他 > 详细

字符串,元组,list,字典间的转换

时间:2018-06-09 19:19:23      阅读:157      评论:0      收藏:0      [点我收藏+]

数组转换成元组
元组转换成数组
数组转换成字典
字符串转换成数组
数组转换成字符串

 

>>> mytuple = (1,2,3)
>>> print list(mytuple) # Tuple to list
[1, 2, 3]
>>>
>>> mylist = [1,2,3] # List to tuple
>>> print tuple(mylist)
(1, 2, 3)
>>>
>>> mylist2 = [ (‘blue‘,5), (‘red‘,3), (‘yellow‘,7) ]
>>> print dict(mylist2) # List to dictionnary
{‘blue‘: 5, ‘yellow‘: 7, ‘red‘: 3}
>>>
>>> mystring = ‘hello‘
>>> print list(mystring) # String to list
[‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘]
>>>
>>> mylist3 = [‘w‘,‘or‘,‘ld‘]
>>> print ‘‘.join(mylist3) # List to string
world
>>>

字符串转换为字典

test.txt ---- {‘key‘:‘name‘,‘value‘:‘passwd‘}

import json

f = open(r‘test.txt‘,‘a+‘,encoding=‘utf-8‘)
f.seek(0)
message = eval(f.read())#这是第一种方法
print(type(message))
print(message)


k= open(r‘test.txt‘,‘a+‘,encoding=‘utf-8‘)
k.seek(0)
info = json.loads(k.read())
#这是第二种方法
print(type(info))
print(info)

字符串,元组,list,字典间的转换

原文:https://www.cnblogs.com/tinazhu/p/9153357.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!