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

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

>>> 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)

猜你喜欢

转载自www.cnblogs.com/tinazhu/p/9153357.html