python中数组,元组,字典和字符串之间的转换
1、字典字典转为字符串
1
2
3
4
>>> dict={'name':'zhzhgo','age':25}
>>> print type(str(dict)),str(dict)
<type 'str'> {'age': 25, 'name': 'zhzhgo'}
>>>
字典转为元组
1
2
3
4
>>> dict={'name':'zhzhgo','age':25}
>>> print type(tuple(dict)),tuple(dict)
<type 'tuple'> ('age', 'name')
>>>
字典转为列表
1
2
3
4
>>> dict={'name':'zhzhgo','age':25}
>>> print type(list(dict)),list(dict)
<type 'list'> ['age', 'name']
>>>
2、元组
元组转为字符串
1
2
3
4
5
6
7
8
>>> mytupe=(1,2,3)
>>> print mytupe.__str__()
(1, 2, 3)
>>>
>>> mylist=('h','e','l','l','o')
>>> print ''.join(mylist)
hello
>>>
元组转为列表
1
2
3
4
>>> mytupe=(1,2,3)
>>> print list(mytupe)
>>>
元组不可以转为字典
3、列表
列表转为字符串
1
2
3
4
>>> mylist=['h','e','l','l','o']
>>> print ''.join(mylist)
hello
>>>
列表转为元组
1
2
3
4
>>> mylist=
>>> print tuple(mylist)
(1, 2, 3)
>>>
列表不可以转为字典
4、字符串
字符串转为元组
1
2
3
4
>>> mystring="hello"
>>> print tuple(mystring)
('h', 'e', 'l', 'l', 'o')
>>>
字符串转为列表
1
2
3
4
>>> mystring="hello"
>>> print list(mystring)
['h', 'e', 'l', 'l', 'o']
>>>
字符串转为字典
1
2
3
4
>>> mystring="{'name':'zhzhgo','age':25}"
>>> print type(eval(mystring))
<type 'dict'>
>>>
页:
[1]