数据类型之间的转换
Tip
有关更多详细信息,请参阅 “文本和图像 ”选项卡!
使用input()函数接受来自用户的数据时,Python始终将其捕获为文本(字符串),即使用户键入数字也是如此。 若要在数学计算中使用该值,必须先显式 转换 (或“cast”)其数据类型。
类型转换函数
Python提供内置函数,用于将数据从一种类型转换为另一种类型。 若要强制转换值,请将其包装在所需的转换函数中:
| 函数 | 转换为 | Example | Result |
|---|---|---|---|
int() |
整数 | int("42") |
42 |
float() |
十进制数 | float("3.14") |
3.14 |
str() |
文本 | str(100) |
"100" |
转换用户输入
下面是将用户输入从文本转换为数字的步骤:
raw_input = input("Enter your score: ") # Captured as text, e.g. "95"
score = float(raw_input) # Convert to a decimal number, e.g. 95.0
print(score + 5) # Math is now possible. Output: 100.0
可以尝试在联机 Python 解释器中 https://aka.ms/python-coder自行运行此代码。
单行速记
可以将这些步骤合并到一行代码中。 在转换函数内嵌套input()函数时,Python首先将用户的输入捕获为文本,然后立即将其转换为所需的类型:
score = float(input("Enter your score: "))
- Python首先运行内部函数:
input("Enter your score: "):获取文本。 - 它立即将该文本传递给外部函数:
float() - 然后,将转换后的数字分配给变量
score。
不兼容的值会发生什么情况?
如果尝试转换无法解释为数字的值,Python停止运行程序并引发:ValueError
user_age = int("hello")
Output:
ValueError: invalid literal for int() with base 10: 'hello'
如果尝试将十进制数转换为整数,还可以获取一个ValueError值,因为Python不能为你舍入它:
user_age = int("3.14") # Pythoncan't drop the decimal for you
如果你认为用户可能键入小数,请使用 float() 而不是 int() 避免此错误。 浮点可以转换为整数,但Python始终向下舍入小数部分(例如int(3.99),变为3)。
检查值的类型
可以使用内置 type() 函数验证任何变量的数据类型:
score = "95"
print(type(score)) # Output: <class 'str'>
score = float(score)
print(type(score)) # Output: <class 'float'>