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功能强大,因为如果某些内容可能以多种不同的方式失败,您可以指定程序在每种失败案例中的反应方式.
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)
首先,try/except不是函数,而是语句.
要在Python中将字符串(或任何其他可以转换的类型)转换为整数,只需调用int()内置函数即可.int()将raise一个ValueError如果失败的话,你应该明确抓住这个:
>>> 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)
语法略有改变:
>>> 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)
不幸的是,官方文档并没有详细说明可能引发的异常int();但是,当您使用 时int(),它实际上可能会引发两个异常:TypeError如果该值不是数字或字符串(或字节或字节数组),并且ValueError该值并未真正映射到数字。
你应该管理两者,像这样:
try:
int_value = int(value)
except (TypeError, ValueError):
print('Not an integer')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90008 次 |
| 最近记录: |