码迷,mamicode.com
首页 > 其他好文 > 详细

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

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

标签:dict   方法   odi   元组   cti   lte   ring   eval   tuple   

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

 

>>> 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,字典间的转换

标签:dict   方法   odi   元组   cti   lte   ring   eval   tuple   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!