介绍
在Python中,数据类型用于对一种特定类型的数据进行分类,确定您可以指定类型的值以及您可以在其中执行的操作. 在编程时,有时我们需要在类型之间转换值,以便以不同的方式来操纵值. 例如,我们可能需要将数字值与字符串结合,或者在数字上代表小数位,这些数字被初始化为整数.
本教程将引导您转换数字,字符串,字符串和列表,并提供示例,以帮助您熟悉不同的用例。
前提条件
您应该在您的计算机或服务器上安装 Python 3 并设置一个编程环境. 如果您没有设置编程环境,可以指: [本地编程环境] (https://www.digitalocean.com/community/tutorial_series/how-to-install-and-set-up-a-local-programming-environment-for-python-3) 或适合您操作系统的 [服务器上的编程环境] (https://www.digitalocean.com/community/tutorial_collections/how-to-install-python-3-and-set-up-a-programming-environment (Ubuntu, CentOS, Debian等) 的安装和设置指南
转换数字类型
在Python中,有两种[数字数据类型] (https://andsky.com/tech/tutorials/understanding-data-types-in-python-3# numbers):[integers] (https://andsky.com/tech/tutorials/understanding-data-types-in-python-3 integers)和[浮点数] (https://andsky.com/tech/tutorials/understanding-data-types-in-python-3# floating-point-numbers)或浮点. 有时,你正在研究别人的代码,需要将整数转换为浮点或反之,或者你可能会发现,当你真正需要的是一个浮点时,你一直在使用整数。 Python有内置方法,可以方便地将整数转换为浮出而将浮出而为整数.
将整数转换为浮动
Python 的方法 float()
将整数转换为 floats. 若要使用此函数,请在列表中添加一个整数:
要跟随本教程中的示例代码,请通过运行python3
命令在本地系统上打开一个Python互动壳,然后您可以复制、粘贴或编辑示例,通过在>>>
提示后添加它们。
1float(57)
在这种情况下,将57
转换为57.0
。
让我们声明f
等于57
,然后打印出新的浮动:
1f = 57
2print(float(f))
1[secondary_label Output]
257.0
通过使用float()
函数,我们可以将整数转换为浮动。
将浮动转换为整合器
Python 也有一个内置的函数来将浮点转换为整数: int()
。
)`函数类似:您可以将浮点数添加到窗口中以将其转换为整数:
1int(390.8)
在这种情况下,将390.8
转换为390
。
让我们声明b
等于125.0
,c
等于390.8
,然后打印出新的浮点:
1b = 125.0
2c = 390.8
3
4print(int(b))
5print(int(c))
1[secondary_label Output]
2125
3390
当使用int()
函数将浮数转换为整数时,Python会切断浮数的十进制和剩余数目,以创建整数。
通过分割转换的数字
在Python 3中,相关量子从整数转换为浮动时做 分区虽然他们不在Python 2](https://andsky.com/tech/tutorials/python-2-vs-python-3-practical-considerations-2)。
1a = 5 / 2
2print(a)
1[secondary_label Output]
22.5
在Python 2中,由于您正在处理两个整数,您将收到一个整数作为您的答案,而不是: 5 / 2 = 2
. 阅读[Python 2 vs Python 3: 实用考虑](https://andsky.com/tech/tutorials/python-2-vs-python-3-practical-considerations-2)
以了解有关Python 2和Python 3之间的差异的更多信息。
使用 Strings 转换
A string 是一个或多个字符(字母,数字,符号)的序列。字符串是计算机程序中常见的数据形式,我们可能需要相当频繁地将字符串转换为数字或数字,特别是当我们考虑用户生成的数据时。
将数字转换为字符串
我们可以通过使用 str()
方法将数字转换为字符串,然后将数字值转换为字符串值。
要将整数)`方法:
1str(12)
当在终端窗口中运行 Python 交互壳中的 str(12)
时,您将收到以下输出:
1[secondary_label Output]
2'12'
数字12周围的引用意味着数字不再是整数,而是现在是一个字符串值。
通过变量,我们可以开始看到将整数转换为字符串是多么实用。假设我们想要跟踪用户的日常编程进度,并且正在输入他们同时写的代码的行数。
1user = "Sammy"
2lines = 50
3
4print("Congratulations, " + user + "! You just wrote " + lines + " lines of code.")
当我们运行此代码时,我们会收到以下错误:
1[secondary_label Output]
2TypeError: can only concatenate str (not "int") to str
我们无法在Python中连接字符串和整数,所以我们必须将变量行
转换为字符串值:
1user = "Sammy"
2lines = 50
3
4print("Congratulations, " + user + "! You just wrote " + str(lines) + " lines of code.")
现在,当我们运行代码时,我们收到以下输出,祝贺我们的用户的进展:
1[secondary_label Output]
2Congratulations, Sammy! You just wrote 50 lines of code.
如果我们要将一个 float 转换为一个字符串,而不是一个整数转换为一个字符串,我们会遵循相同的步骤和格式。当我们将一个 float 传入 `str() 方法时,将返回一个字符串值。
1print(str(421.034))
2
3f = 5524.53
4print(str(f))
1[secondary_label Output]
2421.034
35524.53
我们可以通过连接一个字符串来测试以确保它是正确的:
1f = 5524.53
2print("Sammy has " + str(f) + " points.")
1[secondary_label Output]
2Sammy has 5524.53 points.
我们可以肯定,我们的浮动被正确地转换成一个字符串,因为连接是没有错误的。
将字符串转换为数字
可以通过使用)`方法将字符串转换为数字。
如果你的字符串没有十进制位置,那么你很可能会使用int()
方法将其转换为整数。
让我们用用户Sammy的例子来跟踪每天写的代码行,我们可能希望用数学来操纵这些值,为用户提供更有趣的反馈,但这些值目前存储在字符串中:
1lines_yesterday = "50"
2lines_today = "108"
3
4lines_more = lines_today - lines_yesterday
5
6print(lines_more)
1[secondary_label Output]
2TypeError: unsupported operand type(s) for -: 'str' and 'str'
由于两个数值存储在字符串中,我们收到一个错误:减数的操作符 -
不是两个字符串值的有效操作符。
让我们修改代码以包括将字符串转换为整数的int()
方法,并允许我们用最初是字符串的值进行数学。
1lines_yesterday = "50"
2lines_today = "108"
3
4lines_more = int(lines_today) - int(lines_yesterday)
5
6print(lines_more)
1[secondary_label Output]
258
变量lines_more 自动为整数,在本示例中等于 58 的数值。
我们还可以将上面的示例中的数字转换为浮动值,使用)方法,而不是接收
58的输出,我们将收到
58.0`的输出,一个浮动。
用户 Sammy 在十进制值中获得积分
1total_points = "5524.53"
2new_points = "45.30"
3
4new_total_points = total_points + new_points
5
6print(new_total_points)
1[secondary_label Output]
25524.5345.30
在这种情况下,使用两个字符串的+
术语是一个有效的操作,但它是连接两个字符串,而不是将两个数字值合并在一起。
我们希望在使用float()
方法执行任何数学之前将这些字符串转换为浮动:
1total_points = "5524.53"
2new_points = "45.30"
3
4new_total_points = float(total_points) + float(new_points)
5
6print(new_total_points)
1[secondary_label Output]
25569.83
现在我们已经将两个字符串转换为浮动,我们得到预期的结果,将 45.30
添加到 `5524.53。
如果我们尝试将含有十分数的字符串值转换为整数,我们会收到一个错误:
1f = "54.23"
2print(int(f))
1[secondary_label Output]
2ValueError: invalid literal for int() with base 10: '54.23'
如果我们将字符串中的十进制值传递到int()
方法,我们会收到错误,因为它不会转换为整数。
将字符串转换为数字使我们能够快速修改我们正在处理的数据类型,以便我们可以对最初作为字符串投放的数值执行操作。
转换为双重和列表
您可以使用)`方法将传递给它们的值分别转换为列表和tuple数据类型。
转变为双胞胎
将列表转换为tuple,因为它是一个不变的数据类型,可以允许对我们创建的程序进行实质性的优化。
1print(tuple(['pull request', 'open source', 'repository', 'branch']))
1[secondary_label Output]
2('pull request', 'open source', 'repository', 'branch')
我们看到,在输出中打印出一个,因为项目现在包含在中,而不是方形中。
让我们用‘tuple()’来表示一个列表的变量:
1sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp']
2print(tuple(sea_creatures))
1[secondary_label Output]
2('shark', 'cuttlefish', 'squid', 'mantis shrimp')
再一次,我们看到列表值被更改为tuple值,由窗口表示. 我们可以将任何可迭代类型转换为tuple,包括字符串:
1print(tuple('Sammy'))
1[secondary_label Output]
2('S', 'a', 'm', 'm', 'y')
由于我们可以通过字符串进行迭代,我们可以使用tuple()
方法将它们转换为tuples. 但是,对于不可以迭代的数据类型,如整数和浮动,我们会收到一个类型错误:
1print(tuple(5000))
1[secondary_label Output]
2TypeError: 'int' object is not iterable
虽然可以将整数转换为字符串,然后转换为tuple,如在tuple(str(5000))中,最好选择可读代码,而不是复杂的转换。
转换为列表
将值,特别是tuples,转换为列表,当您需要具有该值的可变版本时,可以是有用的。
我们将使用 list()
方法将下面的 tuple 转换为列表. 因为创建列表的语法使用,请确保包括 list()
方法的,在这种情况下, print()
方法也包括在内:
1print(list(('blue coral', 'staghorn coral', 'pillar coral')))
1[secondary_label Output]
2['blue coral', 'staghorn coral', 'pillar coral']
方块表示列表已从通过list()
方法传递的原始tuple 值返回。
为了使代码更易于读取,我们可以通过使用变量删除其中一对关节:
1coral = ('blue coral', 'staghorn coral', 'pillar coral')
2list(coral)
如果我们打印列表(珊瑚)
,我们将获得与上面相同的输出。
就像tuples一样,字符串可以转换为列表:
1print(list('shark'))
1[secondary_label Output]
2['s', 'h', 'a', 'r', 'k']
在这里,鲨鱼
字符串被转换为列表,提供原始值的可变版本。
结论
这个Python教程展示了如何将一些重要的原生数据类型转换为其他数据类型,主要通过内置的方法。