本文摘自php中文网,作者尚,侵删。

在处理数据的时候,经常需要转换数据的格式,来方便数据遍历等操作。下面我们来看一下Python中的几种数据类型转换。
1、字符串转字典:
1 2 3 | dict_string = "{'name':'linux','age':18}"
to_dict = eval (dict_string)
print (type(to_dict))
|
也可以用json进行转换
1 2 3 4 | import json #如果是Python2.6应该是simplejson
dict_string = "{'name':'linux','age':18}"
to_dict = json.loads(dict_string.replace( "\‘" , "\“" )) #这里需要将字符串的单引号转换成双引号,不然json模块会报错的
print (type(to_dict))
|
2、字典转字符串
同样也可以使用json
1 2 3 4 | import json
dict_1 = { 'name' : 'linux' , 'age' :18}
dict_string = json.dumps(dict_1)
print (type(dict_string))
|
当然也可以直接使用str强制转换
1 2 3 | dict_1 = { 'name' : 'linux' , 'age' :18}
dict_string = str(dict_1)
print (type(dict_string))
|
3、字符串转列表
指定分隔符
1 2 | string1 = "1,2,3,4,5,'aa',12"
print (type(string1.split( ',' )))
|
如果已经是列表格式,直接使用eval即可
1 2 | string2 = "[1,2,3,4,5,'aa',12]"
print (type( eval (string2)))
|
4、列表转字符串
直接使用str强制转换
print(type(str([1,2,3,4,5,'aa',12])))
指定分隔符,注意这里的列表需要都是字符串类型的,不然拼接的时候会报错
print(type("--".join(['a','b','c'])))
5、列表转字典
两个列表,list1 = ['k1','k2','k3'] 、 list2 = [1,2,3] ,转换成字典{’k1‘:1,'k2':2,'k3':3}
1 2 3 | list1 = [ 'k1' , 'k2' , 'k3' ]
list2 = [1,2,3]
print (dict(zip(list1,list2)))
|
更多Python相关技术文章,请访问Python教程栏目进行学习!
以上就是python怎么转换数据类型的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python的序列之列表的通用方法
介绍Python3.6简单操作mysql数据库的方法
浅谈Python中requests模块导入的问题
Python中break和continue语句的差别(实例解析)
django 多数据库配置教程
Python和access的区别
Python中“//”表示什么意思
Python中关于部署的详细介绍
Python打包exe可执行文件
Python模块之time模块介绍
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python怎么转换数据类型