Python字串 元組 列表 字典互相轉換

2021-10-05 17:16:05 字數 2406 閱讀 6454

列表轉字串/元組

字典轉字串/元組/列表

#字串轉元組

a ="123"

print

(tuple

(a))

#結果:('1', '2', '3')

a ="(1,2,3)"

b =eval

(a)print

(b)#結果:(1, 2, 3)

#字串轉列表

a ="123"

print

(list

(a))

#結果:['1', '2', '3']

a ="[1,2,3]"

b =eval

(a)print

(b)#結果:[1, 2, 3]

a ='123'

list1 =

print

(list1)

#結果:[「123」]

#字串轉字典

a =""

b =eval(""

)print

(b)#結果:

#元組轉字串

a =(

'aa'

,'bb'

,'cc'

)b =

''.join(a)

print

(b)#結果:aabbcc

#這種情況先轉成列表

a =(1,

2,3)

list1 =

[str

(i)for i in a]

b =''

.join(list1)

print

(b)print

(type

(b))

#結果:123

#結果:

#元組轉列表

a =(

'aaddff'

,'bb'

,'cc'

)print

(list

(a))

print

(list

(a[0])

)#列表索引為0的字串分隔開,類似可a[1]、a[2]

#結果:['aaddff', 'bb', 'cc']

#結果:['a', 'a', 'd', 'd', 'f', 'f']

#列表轉字串

a =[

'aaddff'

,'bb'

,'cc'

]b =

"".join(a)

print

(b)#結果:aaddffbbcc

a =[1,

2,3]

b =str

(a)print

(b)print

(type

(b))

#結果:[1, 2, 3]

#結果:

a =[1,

2,3]

list1 =

[str

(i)for i in a]

print

(list1)

b =''

.join(list1)

print

(b)print

(type

(b))

#結果:['1', '2', '3']

#結果:123

#結果:

#列表轉元組

a =[1,

2,3]

b =tuple

(a)print

(b)#結果:(1, 2, 3)

#字典轉字串

dict

=print

(type

(str

(dict))

,str

(dict))

#結果:

#字典轉元組(鍵轉元組)

print

(tuple

(dict))

#結果:('gender', 'age', 'name')

#字典轉元組(值轉元組)

print

(tuple

(dict

.values())

)#結果:('male', 18, 'abc')

#字典轉列表(鍵轉列表)

print

(list

(dict))

#結果:['gender', 'age', 'name']

#字典轉列表(值轉列表)

print

(list

(dict

.values())

)#結果:['male', 18, 'abc']

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