MEMOO
MEMOO
Published on 2025-04-17 / 5 Visits
0
0

Python类型转换

摘要:本教程将介绍 Python 中的类型转换及常用转换函数。

Python类型转换简介

在 Python 中,使用 input() 函数可获取用户输入。例如:

value = input('Enter a value:')

print(value)

运行这段代码时,程序会在终端显示输入提示:

Enter a value:

当您输入一个值(例如数字)后,程序将回显该输入值:

Enter a value:100

100

需要注意的是input() 函数返回的是字符串类型而非整型。

下面的示例会提示您输入两个值:净价和税率。随后程序将计算税额并显示结果:

price = input('Enter the price ($):')

tax = input('Enter the tax rate (%):')

tax_amount = price * tax / 100

print(f'The tax amount price is ${tax_amount}')

当你执行程序并输入一些数字:

Enter the price ($):100

Enter the tax rate (%):10

你将得到以下错误:

Traceback (most recent call last):

  File "main.py", line 4, in <module>

    tax_amount = price * tax / 100

TypeError: can't multiply sequence by non-int of type 'str'

由于输入值为字符串类型,因此无法直接使用乘法运算符。

要解决这个问题,您需要在计算前将字符串转换为数值。

使用 int() 函数将字符串转换为整型数值,该函数专门用于实现字符串到整数的转换。

以下示例演示了如何使用 int() 函数将输入字符串转为数值:

price = input('Enter the price ($):')

tax = input('Enter the tax rate (%):')

tax_amount = int(price) * int(tax) / 100

print(f'The tax amount is ${tax_amount}')

运行程序并输入相应数值后,您将看到正确的运算结果:

Enter the price ($):

100

Enter the tax rate (%):

10

The tax amount is $10.0

其他类型转换函数

int(str) 外,Python 还支持以下常用类型转换函数:

  • float(str):将字符串转换为浮点数

  • bool(val):将值转换为布尔值TrueFalse

  • str(val):返回值的字符串表示形式

获取值的类型

要获取值的类型,可使用 type(value) 函数。例如:

result_type = type(100)

print(result_type)

result_type = type(2.0)

print(result_type)

result_type = type('Hello')

print(result_type)

result_type = type(True)

print(result_type)

输出:

<class 'int'>

<class 'float'>

<class 'str'>

<class 'bool'>

输出:

  • 数值 100 的类型为 int(整型)

  • 数值 2.0 的类型为 float(浮点型)

  • 字符串 'Hello' 的类型为 str(字符串型)

  • 布尔值 True 的类型为 bool(布尔型)

总结

  • 使input()函数获取用户输入字符串

  • 使用类型转换函int()float()bool()str(value)将值转换为其他类型

  • 使type()函数获取值的类型


Comment