将具有浮点值的字符串类型转换为整数会引发错误

问题描述 投票:0回答:2

我写了以下代码:

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

文档: https://docs.python.org/3/library/stdtypes.html

python python-2.7
2个回答
0
投票

int()
可以将包含整数文字的字符串转换为
int

它也可以处理浮点数,但它不能(直接)将包含浮点数的字符串转换为

int

您可以将

string
转换为
float
,然后将
float
转换为
int
,如下所示:

print(int(float("3.14")) # prints 3

0
投票

发生错误的原因是您试图将表示浮点数('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)

希望这会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.