Skip to content

Files

Latest commit

48a2448 · Jun 26, 2020

History

History
91 lines (55 loc) · 1.21 KB

12.md

File metadata and controls

91 lines (55 loc) · 1.21 KB

数据类型转换

原文: https://thepythonguru.com/datatype-conversion/


于 2020 年 1 月 7 日更新


偶尔,您会希望将一种类型的数据类型转换为另一种类型。 数据类型转换也称为类型转换。

int转换为float


要将int转换为float,可以使用float()函数。

>>> i = 10
>>> float(i)
10.0

float转换为int


要将float转换为int,您需要使用int()函数。

>>> f = 14.66
>>> int(f)
14

将字符串转换为int


要将string转换为int,请使用int()函数。

>>> s = "123"
>>> int(s)
123

提示

如果字符串包含非数字字符,则int()将引发ValueError异常。

将数字转换为字符串


要将数字转换为字符串,请使用str()函数。

>>> i = 100
>>> str(i)
"100"
>>> f = 1.3
str(f)
'1.3'

舍入数字


四舍五入数字是通过round()函数完成的。

语法round(number[, ndigits])

>>> i = 23.97312
>>> round(i, 2)
23.97

接下来,我们将介绍控制语句