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

时间:2011-11-10 06:47:42

标签: python python-3.x

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

5 个答案:

答案 0 :(得分:60)

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

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

尝试/异常是强大的,因为如果某些内容可能以多种不同的方式失败,您可以指定程序在每种失败案例中的反应方式。

答案 1 :(得分:13)

这是:

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

答案 2 :(得分:7)

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

要在Python中将字符串(or any other type that can be converted)转换为整数,只需调用int()内置函数即可。如果int()失败,raise>>> 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' ValueError,您应该明确地注意到这一点:

在Python 2中。 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'

在Python 3中。 x

语法略有改变:

{{1}}

答案 3 :(得分:0)

在很多情况下,我们希望从用户那里获得一个整数值。用户可能会插入应该被警告的非整数值,并且应该提示他们重试。以下代码段可用于从用户那里获取一个整数值,并继续提示用户插入一个整数,直到输入一个有效整数为止。

def get_integer_value():
  user_value = input("Enter an integer: ")
  try:
    return int(user_value)
  except ValueError:
    print(f"{user_value} is not a valid integer. Please try again.")
    return get_integer_value()


if __name__ == "__main__":
  print(f"You have inserted: {get_integer_value()}")
    

输出:

Enter an integer: asd
asd is not a valid integer. Please try again.
Enter an integer: 32
You have inserted: 32

答案 4 :(得分:-1)

您可以:

try : 
   string_integer = int(string)
except ValueError  :
   print("This string doesn't contain an integer")