python中转换小数
In Python, data types are used to classify one particular type of data, determining the values that you can assign to the type and the operations you can perform on it. When programming, there are times we need to convert values between types in order to manipulate values in a different way. For example, we may need to concatenate numeric values with strings, or represent decimal places in numbers that were initialized as integer values.
在Python中, 数据类型用于对一种特定类型的数据进行分类,确定可以分配给该类型的值以及可以对其执行的操作。 进行编程时,有时需要在类型之间转换值,以便以不同的方式操作值。 例如,我们可能需要将数字值与字符串连接起来,或者在已初始化为整数值的数字中表示小数位。
This tutorial will guide you through converting numbers, strings, tuples and lists, as well as provide examples to help familiarize yourself with different use cases.
本教程将指导您转换数字,字符串,元组和列表,并提供示例以帮助您熟悉不同的用例。
In Python, there are two number data types: integers and floating-point numbers or floats. Sometimes you are working on someone else’s code and will need to convert an integer to a float or vice versa, or you may find that you have been using an integer when what you really need is a float. Python has built-in methods to allow you to easily convert integers to floats and floats to integers.
在Python中,有两种数字数据类型 : 整数和浮点数或浮点数。 有时您正在处理其他人的代码,并且需要将整数转换为浮点数,反之亦然,或者,当您真正需要的是浮点数时,您可能会发现自己一直在使用整数。 Python具有内置方法,可让您轻松地将整数转换为浮点数和将浮点数转换为整数。
Python’s method float()
will convert integers to floats. To use this function, add an integer inside of the parentheses:
Python的方法float()
会将整数转换为浮点数。 要使用此功能,请在括号内添加一个整数:
float(57)
In this case, 57
will be converted to 57.0
.
在这种情况下, 57
将转换为57.0
。
You can also use this with a variable. Let’s declare f
as equal to 57
, and then print out the new float:
您也可以将其与变量一起使用。 让我们声明f
等于57
,然后打印出新的float:
f = 57
print(float(f))
Output
57.0
By using the float()
function, we can convert integers to floats.
通过使用float()
函数,我们可以将整数转换为浮点数。
Python also has a built-in function to convert floats to integers: int()
.
Python还有一个内置函数将float转换为整数: int()
。
The int()
function works similarly to the float()
function: you can add a floating-point number inside of the parentheses to convert it to an integer:
int()
函数的作用类似于float()
函数:您可以在括号内添加一个浮点数,以将其转换为整数:
int(390.8)
In this case, 390.8
will be converted to 390
.
在这种情况下, 390.8
将转换为390
。
You can also use this with variables. Let’s declare b
as equal to 125.0
, and c
as equal to 390.8
, then print out the new floats:
您也可以将其与变量一起使用。 让我们声明b
等于125.0
, c
等于390.8
,然后打印出新的float:
b = 125.0
c = 390.8
print(int(b))
print(int(c))
Output
125
390
When converting floats to integers with the int()
function, Python cuts off the decimal and remaining numbers of a float to create an integer. Even though we may want to round 390.8 up to 391, Python will not do this through the int()
function.
当使用int()
函数将浮点数转换为整数时,Python会截断浮点数的小数和剩余数字以创建一个整数。 即使我们可能希望将390.8舍入为391,Python也不会通过int()
函数来完成此操作。
In Python 3, relevant quotients are converted from integers to floats when doing division though they are not in Python 2. That is, when you divide 5 by 2, in Python 3 you will get a float for an answer (2.5):
在Python 3中,相关的商在进行除法运算时会从整数转换为浮点数,尽管它们不在Python 2中 。 也就是说,当您将5除以2时,在Python 3中,您会得到一个浮点数(2.5):
a = 5 / 2
print(a)
Output
2.5
In Python 2, since you were dealing with two integers, you would receive an integer back as your answer, instead: 5 / 2 = 2
. Read “Python 2 vs Python 3: Practical Considerations” for more information about the differences between Python 2 and Python 3.
在Python 2中,由于您要处理两个整数,因此您将收到一个整数作为答案,而不是: 5 / 2 = 2
。 阅读“ Python 2 vs Python 3:实际考虑事项 ”,以了解有关Python 2和Python 3之间差异的更多信息。
A string is a sequence of one or more characters (letters, numbers, symbols). Strings are a common form of data in computer programs, and we may need to convert strings to numbers or numbers to strings fairly often, especially when we are taking in user-generated data.
字符串是一个或多个字符(字母,数字,符号)的序列。 字符串是计算机程序中数据的一种常见形式,我们可能需要经常将字符串转换为数字或将数字转换为字符串,尤其是在接收用户生成的数据时。
We can convert numbers to strings through using the str()
method. We’ll pass either a number or a variable into the parentheses of the method and then that numeric value will be converted into a string value.
我们可以使用str()
方法将数字转换为字符串。 我们将数字或变量传递到方法的括号中,然后该数字值将转换为字符串值。
Let’s first look at converting integers. To convert the integer 12
to a string value, you can pass 12
into the str()
method:
让我们首先看一下转换整数。 要将整数12
转换为字符串值,可以将12
传递给str()
方法:
str(12)
When running str(12)
in the Python interactive shell with the python
command in a terminal window, you’ll receive the following output:
在终端窗口中使用python
命令在Python交互式外壳中运行str(12)
时,将收到以下输出:
Output
'12'
The quotes around the number 12 signify that the number is no longer an integer but is now a string value.
数字12周围的引号表示该数字不再是整数,而是一个字符串值。
With variables we can begin to see how practical it can be to convert integers to strings. Let’s say we want to keep track of a user’s daily programming progress and are inputting how many lines of code they write at a time. We would like to show this feedback to the user and will be printing out string and integer values at the same time:
使用变量,我们可以开始了解将整数转换为字符串的实用性。 假设我们要跟踪用户的日常编程进度,并输入他们一次编写多少行代码。 我们希望向用户显示此反馈,并将同时打印出字符串和整数值:
user = "Sammy"
lines = 50
print("Congratulations, " + user + "! You just wrote " + lines + " lines of code.")
When we run this code, we receive the following error:
当我们运行此代码时,我们收到以下错误:
Output
TypeError: Can't convert 'int' object to str implicitly
We’re not able to concatenate strings and integers in Python, so we’ll have to convert the variable lines
to be a string value:
我们无法在Python中连接字符串和整数,因此我们必须将变量lines
转换为字符串值:
user = "Sammy"
lines = 50
print("Congratulations, " + user + "! You just wrote " + str(lines) + " lines of code.")
Now, when we run the code, we receive the following output that congratulates our user on their progress:
现在,当我们运行代码时,我们收到以下输出,祝贺我们的用户前进:
Output
Congratulations, Sammy! You just wrote 50 lines of code.
If we are looking to convert a float to a string rather than an integer to a string, we follow the same steps and format. When we pass a float into the str()
method, a string value of the float will be returned. We can use either the float value itself or a variable:
如果希望将浮点数转换为字符串,而不是将整数转换为字符串,请遵循相同的步骤和格式。 当我们将float传递给str()
方法时,将返回float的字符串值。 我们可以使用float值本身或变量:
print(str(421.034))
f = 5524.53
print(str(f))
Output
421.034
5524.53
We can test to make sure it’s right by concatenating with a string:
我们可以通过连接一个字符串来测试以确保它是正确的:
f = 5524.53
print("Sammy has " + str(f) + " points.")
Output
Sammy has 5524.53 points.
We can be sure our float was properly converted to a string because the concatenation was performed without error.
我们可以确定我们的浮点数已正确转换为字符串,因为连接已正确执行。
Strings can be converted to numbers by using the int()
and float()
methods.
可以使用int()
和float()
方法将字符串转换为数字。
If your string does not have decimal places, you’ll most likely want to convert it to an integer by using the int()
method.
如果您的字符串没有小数位,您很可能希望使用int()
方法将其转换为整数。
Let’s use the example of the user Sammy keeping track of lines of code written each day. We may want to manipulate those values with math to provide more interesting feedback for the user, but those values are currently stored in strings:
让我们以用户Sammy跟踪每天编写的代码行为例。 我们可能希望通过数学操作这些值,以为用户提供更多有趣的反馈,但是这些值当前存储在字符串中:
lines_yesterday = "50"
lines_today = "108"
lines_more = lines_today - lines_yesterday
print(lines_more)
Output
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Because the two numeric values were stored in strings, we received an error. The operand -
for subtraction is not a valid operand for two string values.
由于两个数值存储在字符串中,因此我们收到了错误消息。 操作数-
减法不是两个字符串值有效的操作数。
Let’s modify the code to include the int()
method that will convert the strings to integers, and allow us to do math with values these that were originally strings.
让我们修改代码以包括int()
方法,该方法会将字符串转换为整数,并允许我们使用原始字符串的值进行数学运算。
lines_yesterday = "50"
lines_today = "108"
lines_more = int(lines_today) - int(lines_yesterday)
print(lines_more)
Output
58
The variable lines_more
is automatically an integer, and it is equal to the numeric value of 58 in this example.
变量lines_more
自动是一个整数,在此示例中,它等于数值58。
We can also convert the numbers in the example above to float values by using the float()
method in place of the int()
method. Instead of receiving the output of 58
, we’ll receive the output of 58.0
, a float.
我们还可以使用float()
方法代替int()
方法,将上述示例中的数字转换为float值。 而不是接收58
的输出,我们将接收58.0
的输出,即浮点数。
The user Sammy is earning points in decimal values
用户Sammy用十进制值赢得积分
total_points = "5524.53"
new_points = "45.30"
new_total_points = total_points + new_points
print(new_total_points)
Output
5524.5345.30
In this case, using the +
operand with two strings is a valid operation, but it is concatenating two strings rather than adding two numeric values together. So, our output looks unusual since it just places the two values next to each other.
在这种情况下,将+
操作数与两个字符串一起使用是有效的操作,但它是将两个字符串连接在一起,而不是将两个数值加在一起。 因此,我们的输出看起来很不寻常,因为它只是将两个值彼此相邻放置。
We’ll want to convert these strings to floats prior to performing any math with the float()
method:
在使用float()
方法执行任何数学运算之前,我们希望将这些字符串转换为浮点数:
total_points = "5524.53"
new_points = "45.30"
new_total_points = float(total_points) + float(new_points)
print(new_total_points)
Output
5569.83
Now that we have converted the two strings to floats, we receive the anticipated result that adds 45.30
to 5524.53
.
现在,我们已经将两个字符串转换为浮点数,我们收到了将45.30
添加到5524.53
的预期结果。
If we try to convert a string value with decimal places to an integer, we’ll receive an error:
如果我们尝试将带小数位的字符串值转换为整数,则会收到错误消息:
f = "54.23"
print(int(f))
Output
ValueError: invalid literal for int() with base 10: '54.23'
If we pass a decimal value in a string to the int()
method we’ll receive an error because it will not convert to an integer.
如果我们将字符串中的十进制值传递给int()
方法,则会收到错误消息,因为它不会转换为整数。
Converting strings to numbers enables us to quickly modify the data type we are working with so that we can perform operations on numeric values that were originally cast as strings.
将字符串转换为数字使我们能够快速修改正在使用的数据类型,以便我们可以对最初转换为字符串的数值执行操作。
You can use the methods list()
and tuple()
to convert the values passed to them into the list and tuple data type respectively. In Python:
您可以使用方法list()
和tuple()
将传递给它们的值分别转换为list和tuple数据类型。 在Python中:
a list is a mutable ordered sequence of elements that is contained within square brackets [ ]
.
列表是包含在方括号[ ]
的可变的有序元素序列。
a tuple is an immutable ordered sequence of elements contained within parentheses ( )
.
元组是括号( )
包含的元素的不可变有序序列。
Let’s start with converting a list to a tuple. Converting a list to a tuple, because it’s an immutable data type, can allow substantial optimization to the programs that we create. When we use the method tuple()
it will return the tuple version of the value passed to it.
让我们从将列表转换为元组开始。 将列表转换为元组是一种不可变的数据类型,因此可以对我们创建的程序进行实质性的优化。 当我们使用方法tuple()
,它将返回传递给它的值的元组版本。
print(tuple(['pull request', 'open source', 'repository', 'branch']))
Output
('pull request', 'open source', 'repository', 'branch')
We see that a tuple is printed out in the output, as the items are now contained within parentheses rather than square brackets.
我们看到输出中已打印出一个元组,因为这些项现在包含在括号中而不是方括号中。
Let’s use tuple()
with a variable that represents a list:
让我们将tuple()
与代表列表的变量一起使用:
sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp']
print(tuple(sea_creatures))
Output
('shark', 'cuttlefish', 'squid', 'mantis shrimp')
Again, we see that the list value is changed to a tuple value, indicated by the parentheses. We can convert any iterable type to a tuple, including strings:
再次,我们看到列表值更改为元组值,由括号表示。 我们可以将任何可迭代类型转换为元组,包括字符串:
print(tuple('Sammy'))
Output
('S', 'a', 'm', 'm', 'y')
Because we can iterate through strings, we can convert them to tuples with the tuple()
method. With data types that are not iterable, however, like integers and floats, we will receive a type error:
因为我们可以遍历字符串,所以可以使用tuple()
方法将它们转换为元tuple()
。 但是,对于不可迭代的数据类型,例如整数和浮点数,我们将收到类型错误:
print(tuple(5000))
Output
TypeError: 'int' object is not iterable
While it is possible to convert the integer to a string and then convert to a tuple, as in tuple(str(5000))
, it is best to opt for readable code over complicated conversions.
尽管可以将整数转换为字符串,然后转换为元组,如tuple(str(5000))
,但最好选择可读代码,而不要进行复杂的转换。
Converting values, especially tuples, to lists can be useful when you need to have a mutable version of that value.
当您需要该值的可变版本时,将值(尤其是元组)转换为列表会很有用。
We’ll use the list()
method to convert the following tuple to a list. Because the syntax for creating a list uses parentheses, be sure to include the parentheses of the list()
method, and in this case the print()
method as well:
我们将使用list()
方法将以下元组转换为列表。 因为创建列表的语法使用括号,所以请确保包括list()
方法的括号,在这种情况下, print()
方法:
print(list(('blue coral', 'staghorn coral', 'pillar coral')))
Output
['blue coral', 'staghorn coral', 'pillar coral']
The square brackets signal that a list has been returned from the original tuple value that was passed through the list()
method.
方括号表示已通过list()
方法传递的原始元组值返回了list()
。
To make the code more readable, we can remove one of the pairs of parentheses by using a variable:
为了使代码更具可读性,我们可以使用变量来删除一对括号中的一对:
coral = ('blue coral', 'staghorn coral', 'pillar coral')
list(coral)
If we print list(coral)
we would receive the same output as above.
如果我们打印list(coral)
我们将收到与上述相同的输出。
Just like tuples, strings can be converted to lists:
就像元组一样,字符串也可以转换为列表:
print(list('shark'))
Output
['s', 'h', 'a', 'r', 'k']
Here the string 'shark'
was converted to a list, providing a mutable version of the original value.
在这里,字符串'shark'
被转换为列表,提供了原始值的可变版本。
This Python tutorial demonstrated how to convert several of the important native data types to other data types, primarily through built-in methods. Being able to convert data types in Python provides you with extra flexibility when writing your programs.
该Python教程演示了如何主要通过内置方法将几种重要的本机数据类型转换为其他数据类型。 能够在Python中转换数据类型为您在编写程序时提供了额外的灵活性。
翻译自: https://www.digitalocean.com/community/tutorials/how-to-convert-data-types-in-python-3
python中转换小数