使用Python中的try/except将String转换为Int

use*_*163 43 python python-3.x

所以我很沮丧如何使用try/except函数将字符串转换为int.有谁知道如何做到这一点的简单功能?我觉得我对字符串和整体仍然有点朦胧.我非常有信心整数与数字有关.字符串......不是那么多.

Nat*_*nes 65

重要的是具体说明在尝试使用try/except块时要尝试捕获的异常.

string = "abcd"
try:
    i = int(string)
    print i
except ValueError:
    #Handle the exception
    print 'Please enter an integer'
Run Code Online (Sandbox Code Playgroud)

Try/Excepts功能强大,因为如果某些内容可能以多种不同的方式失败,您可以指定程序在每种失败案例中的反应方式.

  • 只是想提一下...如果您要转换的变量有可能是“None”,那么您将希望您的 except 块为“ except (TypeError, ValueError):” (7认同)
  • 具体为+1.值得注意的是,`ValueError``Exception`实例将包含更多信息,*即.*"int()的无效文字,基数为10:'abcd'". (4认同)

gec*_*cco 16

这里是:

s = "123"
try:
  i = int(s)
except ValueError as verr:
  pass # do job to handle: s does not contain anything convertible to int
except Exception as ex:
  pass # do job to handle: Exception occurred while converting to int
Run Code Online (Sandbox Code Playgroud)

  • 抓住超过你需要的是**非常糟糕的做法.调整你的答案,我很乐意改变我的投票. (10认同)
  • -1用于捕获几乎所有可能的异常,而不仅仅是"ValueError".你应该只抓住你知道如何处理的东西. (5认同)
  • 你是对的.为了更好的SO内容. (2认同)
  • +1 这只是一个示例,因此显示捕获 ValueError 以及其他类型异常的模式非常具有指导性。例如,解析参数并在无效或未定义时设置默认值非常有用。 (2认同)

Joh*_*web 9

首先,try/except不是函数,而是语句.

要在Python中将字符串(或任何其他可以转换的类型)转换为整数,只需调用int()内置函数即可.int()raise一个ValueError如果失败的话,你应该明确抓住这个:

在Python 2. x中:

>>> for value in '12345', 67890, 3.14, 42L, 0b010101, 0xFE, 'Not convertible':
...     try:
...         print '%s as an int is %d' % (str(value), int(value))
...     except ValueError as ex:
...         print '"%s" cannot be converted to an int: %s' % (value, ex)
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'
Run Code Online (Sandbox Code Playgroud)

在Python 3. x

语法略有改变:

>>> for value in '12345', 67890, 3.14, 42, 0b010101, 0xFE, 'Not convertible':
...     try:
...         print('%s as an int is %d' % (str(value), int(value)))
...     except ValueError as ex:
...         print('"%s" cannot be converted to an int: %s' % (value, ex))
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'
Run Code Online (Sandbox Code Playgroud)

  • +1表示Python 2.x和3.x语法差异. (2认同)
  • "ValueError"是唯一预期的异常吗? - 文档没有指定:https://docs.python.org/2/library/functions.html#int (2认同)
  • `int()`也可以引发`TypeError`。 (2认同)

rob*_*rob 5

不幸的是,官方文档并没有详细说明可能引发的异常int();但是,当您使用 时int(),它实际上可能会引发两个异常:TypeError如果该值不是数字或字符串(或字节或字节数组),并且ValueError该值并未真正映射到数字。

你应该管理两者,像这样:

try:
   int_value = int(value)
except (TypeError, ValueError):
    print('Not an integer')
Run Code Online (Sandbox Code Playgroud)