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

2021-09-22 12:31:54 字數 1101 閱讀 9847

1 #-*-coding:utf-8-*-

2 3 #1、字典

4 dict =

5 6 #字典轉為字串,返回:

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 #字串轉為字典,返回:48 print type(eval(""))

複製**

python字串 元組 列表 字典互轉

coding utf 8 1 字典 dict 字典轉為字串,返回 print type str dict str dict 字典可以轉為元組,返回 age name class print tuple dict 字典可以轉為元組,返回 7,zara first print tuple dict.va...

python字串 元組 列表 字典互轉

coding utf 8 1 字典 dict 字典轉為字串,返回 print type str dict str dict 字典可以轉為元組,返回 age name class print tuple dict 字典可以轉為元組,返回 7,zara first print tuple dict.va...

python字串 元組 列表 字典互轉

coding utf 8 1 字典 dict 字典轉為字串,返回 print type str dict str dict 字典可以轉為元組,返回 age name class print tuple dict 字典可以轉為元組,返回 7,zara first print tuple dict.va...