使用Python中的Number()函数进行数字转换
发布时间:2023-12-17 03:31:25
Python中的Number()函数不是内置函数之一。如果你想将一个值转换为数字,可以使用int()、float()或complex()函数,具体取决于你要将值转换为哪种类型的数字。
下面是分别使用int()、float()和complex()函数将一个值转换为整型、浮点型和复数型的例子:
#### 使用int()将值转换为整型:
number1 = int("10") # 字符串转换为整型
print(number1) # 输出: 10
number2 = int(3.14) # 浮点数转换为整型
print(number2) # 输出: 3
number3 = int(True) # 布尔值转换为整型
print(number3) # 输出: 1
number4 = int("Hello") # 无法将非数字字符转换为整型,会引发 ValueError 异常
#### 使用float()将值转换为浮点型:
number1 = float(3) # 整型转换为浮点型
print(number1) # 输出: 3.0
number2 = float("3.14") # 字符串转换为浮点型
print(number2) # 输出: 3.14
number3 = float(True) # 布尔值转换为浮点型
print(number3) # 输出: 1.0
#### 使用complex()将值转换为复数型:
number1 = complex(3) # 实部为整型,虚部为0
print(number1) # 输出: (3+0j)
number2 = complex(3.14) # 实部为浮点型,虚部为0
print(number2) # 输出: (3.14+0j)
number3 = complex(3, 4) # 实部为整型,虚部为整型
print(number3) # 输出: (3+4j)
number4 = complex("3.14+2j") # 字符串转换为复数型
print(number4) # 输出: (3.14+2j)
上述例子中,int()、float()和complex()函数分别将字符串、整型、浮点型和布尔值等不同类型的值转换为了整型、浮点型和复数型的数字。需要注意的是,如果将无法转换的值作为参数传递给这些函数,就会引发相应的异常。
