整理了最全的Python3数据类型转换方法,可以收藏当手册用
本文基于python3.8版本,总结了各种数据类型直接的转换规则和方法。算是比较全了,可以收藏当手册来查。
概述
数据类型转换,指的是通过某种方法,将一个数据由原来的类型转换为另外一个类型。比如,我们将字符串“123”转换为数字123,这就是一种数据类型的转换。
Python支持各种标准数据类型之间的转换,但并不是任意数据都可以转换的,所有的转换要符合“常理”,逻辑上应该是成立的。比如,你不应该试图将一个complex类型转换为int,因为python也不知该怎么转换。
数据类型转换支持情况汇总表
下面我整理了python3数据类型之间转换的支持情况(这应该是最全的了):

各种类型之间的转换及实例
转换为int
print(int(1.2)) # float -> int
print(int('')) # string -> int
print(int(b'')) # bytes -> int
print('0x%x' % (int.from_bytes(b'', byteorder='little', signed=True)))
print(int(True)) # bool -> int
转换为float
print(float('1.2')) # string->float
print(float(b'3.4')) # bytes -> float
print(float(123)) # int->float
print(float(False)) # bool->float
转换为bool
所有类型都可以转换为bool型
print(bool(1)) # int->bool
print(bool(0.0)) # float->bool
print(bool(0 + 0j)) # complex->bool
print(bool('')) # string->bool, 空字符串为False,其它都是True
print(bool(b'hello')) # bytes->bool, 空为False,其它都是True
print(bool.from_bytes(b'\x00', byteorder='little')) # bytes->bool
print(bool([])) # list->bool, 空为False,其它都是True
print(bool(())) # tuple->bool, 空为False,其它都是True
print(bool({})) # dict->bool, 空为False,其它都是True
print(bool(set())) # set->bool, 空为False,其它都是True
转换为complex
print(complex(100)) # int->complex
print(complex(1.2)) # float->complex
print(complex(True)) # bool->complex
print(complex('1.2+2.3j')) # string->complex
转换为string
所有基本类型都可以转换为string
print(b'hello'.decode('utf-8')) # bytes->string
print(str(1)) # int->string
print(str(1.2)) # float->string
print(str(True)) # bool->string
print(str(1.2 + 2.3j)) # complex->string其它都是True
print(str(['hello', 100])) # list->string
print(str(('hello', 100))) # tuple->string
print(str({'name': 'xiaowang', 'age': 20})) # dict->string
print(str({'name', 'age'})) # set->string
转换为bytes
因为所有类型都可以转换为string,而string可以转换为bytes,所以所有类型都可以间接转换为bytes。
下面我们只讨论直接转换为bytes的类型
print('bytes'.center(30, '*'))
print(b'\x64') # int转bytes
print(int.to_bytes(100, byteorder='big', signed=True, length=2)) # int转bytes
print(bool.to_bytes(True, byteorder='big', signed=True, length=2)) # bool转bytes
print('hello'.encode(encoding='utf-8')) # string转bytes
print(bytes([1, 200, 80, 50])) # list转bytes
print(bytes((1, 200, 80, 50))) # tuple转bytes
print(bytes({1, 200, 80, 50})) # set转bytes
转换为list
print(list("hello")) # string->list
print(list(b'hello')) # bytes->list
print(list((100, 200, 300))) # tuple->list
print(list({'name', 'age'})) # set->list
print(list({'name': 'xiaowang', 'age': 20})) # dict->list, 只取key值
转换为tuple
print(tuple("hello")) # string->tuple
print(tuple(b"hello")) # bytes->tuple
print(tuple([100, 200, 300])) # list->tuple
print(tuple({'name', 'age'})) # set->tuple
print(tuple({'name': 'xiaowang', 'age': 20})) # dict->tuple, 只取key值
转换为set
print(set("hello")) # string->set
print(set(b"hello")) # bytes->set
print(set([100, 200, 300])) # list->set
# print(set([100, 200, [300, 400]])) # list->set, list中包含可变数据类型,报异常
print(set(('name', 'age'))) # tuple->set
# print(set(('name', 'age', []))) # tuple->set,包含可变数据类型,报异常
print(set({'name': 'xiaowang', 'age': 20})) # dict->set, 只取key值
转换为dict
转换为dict的方法略微复杂一些
1、string->dict
方式一、使用json转换,字符串格式需要严格按照json格式来
user_str = '{"name": "xiaowang", "city": "Chengdu", "age": 28}'
import json
print(json.loads(user_str))
方式二、使用eval函数转换,eval有安全隐患,不建议使用
print(eval(user_str))
方式三、 使用ast.literal_eval
import ast
print(ast.literal_eval(user_str))
2、list->dict
方式一、需要用到zip
user_keys = ['name', 'city', 'age']
user_values = ['xiaowang', 'Chengdu', 28]
print(dict(zip(user_keys, user_values)))
方式二、二维列表
user_info = [
["name", "xiaowang"],
["city", "Chengdu"],
["age", 28]
]
print(dict(user_info))
set->dict tuple->dict的方式和list->dict一样
我的更多文章和专栏:
整理了最全的Python3数据类型转换方法,可以收藏当手册用的更多相关文章
- 整理的最全 python常见面试题
整理的最全 python常见面试题(基本必考)① ②③④⑤⑥⑦⑧⑨⑩ 1.大数据的文件读取: ① 利用生成器generator: ②迭代器进行迭代遍历:for line in file; 2.迭代 ...
- 整理的最全 python常见面试题(基本必考)
整理的最全 python常见面试题(基本必考) python 2018-05-17 作者 大蛇王 1.大数据的文件读取 ① 利用生成器generator ②迭代器进行迭代遍历:for line in ...
- 自己花了2天时间,重新整理了个全面的vue2的模板
自己花了2天时间,重新整理了个全面的vue2的模板,基本vue中需要的部分都整理封装好了,希望大家喜欢^ ^.欢迎大家star或者fork呀~,https://github.com/qianxiaon ...
- SQL Server游标 C# DataTable.Select() 筛选数据 什么是SQL游标? SQL Server数据类型转换方法 LinQ是什么? SQL Server 分页方法汇总
SQL Server游标 转载自:http://www.cnblogs.com/knowledgesea/p/3699851.html. 什么是游标 结果集,结果集就是select查询之后返回的所 ...
- 整理全网最全K8S集群管理工具、平台
整理常见的整理全网最全K8S集群管理工具.平台解决方案. 1 Rancher Rancher中文官网:https://docs.rancher.cn/ 2 KubeSphere 官网:https:// ...
- python3 数据类型
Python3 中有六个标准的数据类型: Number(数字) String(字符串) List(列表) Tuple(元组) Sets(集合) Dictionary(字典) Number(数字) Py ...
- python3数据类型
python基本数据类型 Python3 中有六个标准的数据类型: Number(数字) String(字符串) List(列表) Tuple(元组) Sets(集合) Dictionary(字典) ...
- python3数据类型--数字
数字 Python数字数据类型用于存储数值.数字数据类型是不允许改变的,所以如果改变数字数据类型的值,将重新分配内存空间. 以下实例在变量赋值时Number对象被创建: #!/usr/bin/env ...
- Python3数据类型及转换
I. 数据类型 Python3将程序中的任何内容统称为对象(Object),基本的数据类型有数字和字符串等,也可以使用自定义的类(Classes)创建新的类型. Python3中有六个标准的数据类型: ...
随机推荐
- JS Math&Date的方法 (上)
数学对象&时间对象 本篇文章主要介绍Math 和 Date 的常用方法! 一 :Math & Date Math 数学对象 - 处理数学计算和数学类 ...
- [PHP][mysql] 需要知道的那些事
就是想总结一下自己不会的! sql: 1.在SQL语句中出现AS,是起别名的意思! 例子:select a.* from table_1 as a就是给table_1起个别名叫a,因此前面就可以使用a ...
- 使用RNN对文本进行分类实践电影评论
本教程在IMDB大型影评数据集 上训练一个循环神经网络进行情感分类. from __future__ import absolute_import, division, print_function, ...
- python数据分析工具——Pandas、StatsModels、Scikit-Learn
Pandas Pandas是 Python下最强大的数据分析和探索工具.它包含高级的数据结构和精巧的工具,使得在 Python中处理数据非常快速和简单. Pandas构建在 Numpy之上,它使得以 ...
- 【arithmetic】搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引.如果目标值不存在于数组中,返回它将会被按顺序插入的位置 可以假设数组中无重复元素. 示例 1: 输入: [1,3,5,6], 5 输出: ...
- prefetch 和 preload 及 webpack 的相关处理
使用预取和预加载是网站性能和用户体验提升的一个很好的途径,本文介绍了使用 prefetch 和 prefetch 进行预取和预加载的方法,并使用 webpack 进行实现 Link 的链接类型 < ...
- 百度云BaaS体系揭秘,突破共识机制、单机计算和串行处理三大瓶颈
区块链作为去中心化的技术机制拥有广泛的应用场景与市场潜能.自2017年爆发式增长后,区块链虽然已经进入平稳期,但仍然存在概念混淆.技术性能制约.智能合约制约.共识机制.网络建设等痛点.为了打破行业壁垒 ...
- APP路由还能这样玩
本文主要讲述一种设计思路,组件化架构市面上已经有很多大厂成熟的方案,但是在组件化过程中,偶尔会遇到2个独立业务子模块间没有相互引用,也需要能直接调用对方的功能,因此我想到通过方法路由来解决,如果还有疑 ...
- JAVA编程思想 Ch3.5题
练习5:创建一个class类,包含连两个String字段 :name.says.在main方法中创建两个Dog方法 一个命名为spot 叫声为 Ruff,另一个命民为scruffy,叫声为:Wuff: ...
- Codeforces Round 623(Div. 2,based on VK Cup 2019-2020 - Elimination Round,Engine)D. Recommendations
VK news recommendation system daily selects interesting publications of one of n disjoint categories ...