Python 将字符串转换为 int 的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41837247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:42:26  来源:igfitidea点击:

Short way to convert string to int

pythonpython-3.xtype-conversion

提问by Sam Banks

I usually do this to convert string to int:

我通常这样做是为了将字符串转换为 int:

my_input = int(my_input)

but I was wondering if there was a less clumsy way, because it feels kind of long.

但我想知道是否有一种不那么笨拙的方式,因为感觉有点长。

回答by Gonzalo

my_input = int(my_input)

There is no shorter way than using the intfunction (as you mention)

没有比使用int函数更短的方法(正如你所提到的)

回答by biocyberman

Maybe you were hoping for something like my_number = my_input.to_int. But it is not currently possible to do it natively. And funny enough, if you want to extract the integer part from a float-like string, you have to convert to floatfirst, and then to int. Or else you get ValueError: invalid literal for int().

也许你希望得到类似的东西my_number = my_input.to_int。但目前无法在本地进行。有趣的是,如果你想从一个类似浮点数的字符串中提取整数部分,你必须先转换为float,然后转换为int。否则你得到ValueError: invalid literal for int().

The robust way:

健壮的方法:

my_input = int(float(my_input))

For example:

例如:

>>> nb = "88.8"
>>> int(nb)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '88.8'
>>> int(float(nb))
88

回答by Jan Meeuwissen

If it is user input, chances are the user inputted a string. So better catch the exception as well with try:

如果是用户输入,则很可能是用户输入了一个字符串。所以更好地捕捉异常以及try

user_input = '88.8'
try:
    user_input = int(float(user_input))
except:
    user_input = 0
print(user_input)