python怎么转换数据类型


本文摘自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如何进行进制转换

Python 数据流操作

Python中如何合并两个字典教程

Python中@property装饰器的技巧性用法(代码示例)

Python如何将字符串等长分割

Python中元类与枚举类的介绍(代码示例)

Python中“//”表示什么?

Python能做什么工作

Python37中如何安装pip

Python fromkeys函数是什么?fromkeys函数的作用是什么?

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...