1
、
str
轉(zhuǎn)
dict
1 #
借助
eval,dict
2 str="{"data":"123","result":"ok"}"
3 dict1=dict(eval(str))
4 #
關(guān)于
eval()
的說法
,
官方
demo
解釋為:將字符串str
當(dāng)成有效的表達(dá)式來求值并返回計(jì)算結(jié)果
5
6
7 #
借助
json
8 import json
9 str="{"data":"123","result":"ok"}"10 dict1=json.loads(str)
View Code
2
、
dict
轉(zhuǎn)
str
1 #
借助
str2 dict1={'name':'yizhenfeng','age':'27'}3 str1=str(dict1)4 5 #
通過遍歷
dict
中的所有元素
6 dict1={'name':'yizhenfeng','age':'27'}7for key,value in dict1.items():8 print("\"%s\":\"%s\"" % (key,value))
View Code
3
、
str
轉(zhuǎn)
list
1 #
借助
list2 str="yizhenfeng"3 list1=list(str)4 5 #
借助
split6 str="yi zhen feng"7 list1=str.split() #
或者
list1=str.split(" ")
View Code
4
、
list
轉(zhuǎn)
str
1 #
借助
"".join(list)
,其中引號中是字符之間的分割符,如
“,”
,
“;”
,
“\t”
等等
2 list1=["yi","zhen","feng"]3 str="".join(list1) #
輸出
"yizhenfeng"4 5 str1="."join(list1) #
輸出
"yi.zhen.feng"
View Code
5
、
json
轉(zhuǎn)
dict
1 #
借助
json.loads()2 jsonstr={"name": "yizhenfeng", "age": "27"}3 dict1=json.loads(jsonstr)4 print(dict1)5 #{'name': 'yizhenfeng', 'age': '27'}
View Code
6
、
dict
轉(zhuǎn)
json
1 #
借助
json.dumps()2 import json3 dict1={'name': 'yizhenfeng', 'age': '27'}4 jsonstr=json.dumps(dict1)5 print(jsonstr)6 #{"name": "yizhenfeng", "age": "27"}
View Code
來源:
博客園