python 字符串,元組, 列表,字典之間的轉換


 1 #-*-coding:utf-8-*-
 2 
 3 #1、字典
 4 dict = {'name': 'Zara', 'age': 7, 'class': 'First'}
 5 
 6 #字典轉為字符串,返回:<type 'str'> {'age': 7, 'name': 'Zara', 'class': 'First'}
 7 print type(str(dict)), str(dict)
 8 
 9 #字典可以轉為元組,返回:('age', 'name', 'class')
10 print tuple(dict)
11 #字典可以轉為元組,返回:(7, 'Zara', 'First')
12 print tuple(dict.values())
13 
14 #字典轉為列表,返回:['age', 'name', 'class']
15 print list(dict)
16 #字典轉為列表
17 print dict.values
18 
19 #2、元組
20 tup=(1, 2, 3, 4, 5)
21 
22 #元組轉為字符串,返回:(1, 2, 3, 4, 5)
23 print tup.__str__()
24 
25 #元組轉為列表,返回:[1, 2, 3, 4, 5]
26 print list(tup)
27 
28 #元組不可以轉為字典
29 
30 #3、列表
31 nums=[1, 3, 5, 7, 8, 13, 20];
32 
33 #列表轉為字符串,返回:[1, 3, 5, 7, 8, 13, 20]
34 print str(nums)
35 
36 #列表轉為元組,返回:(1, 3, 5, 7, 8, 13, 20)
37 print tuple(nums)
38 
39 #列表不可以轉為字典
40 
41 #4、字符串
42 
43 #字符串轉為元組,返回:(1, 2, 3)
44 print tuple(eval("(1,2,3)"))
45 #字符串轉為列表,返回:[1, 2, 3]
46 print list(eval("(1,2,3)"))
47 #字符串轉為字典,返回:<type 'dict'>
48 print type(eval("{'name':'ljq', 'age':24}"))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM