我写了以下代码:
typConvInt = int('3.3')
print(typConvInt)
但是编译器抛出错误。
错误消息:
Traceback (most recent call last):
File "E:\Trainings\Python_Training\HelloWorld.py", line 285, in <module>
intconv3 = int('3.3')
^^^^^^^^^^
ValueError: invalid literal for int() with base 10: '3.3'
版本:Python 2.7.7
我尝试将浮点值更改为整数值,它有效,但浮点字符串到整数转换仍然失败
conv1 = int('3')
print(conv1)
# this is passed
conv2 = int('3.0')
print(conv2)
# this code is still failing but the tutorial says this will work and return as 3
int()
可以将包含整数文字的字符串转换为 int
。
它也可以处理浮点数,但它不能(直接)将包含浮点数的字符串转换为
int
。
您可以将
string
转换为 float
,然后将 float
转换为 int
,如下所示:
print(int(float("3.14")) # prints 3
发生错误的原因是您试图将表示浮点数('3.3'或'3.0')的字符串直接转换为int,这在Python中是不允许的。 int() 函数需要一个表示整数的字符串。
要将浮点字符串转换为整数,您需要先将字符串转换为浮点,然后再将浮点转换为整数。
# First convert the string to a float
fVal= float('3.3')
# Then convert the float to an integer
intVal= int(fVal)
print(intVal)
希望这会有所帮助