【问题标题】:Converting String to Int using try/except in Python在 Python 中使用 try/except 将字符串转换为 Int
【发布时间】:2011-11-10 06:47:41
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    在使用 try/except 块时,请务必具体说明您要捕获的异常。

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

    Try/Excepts 非常强大,因为如果某事可能以多种不同的方式失败,您可以指定您希望程序在每种失败情况下如何反应。

    【讨论】:

    • +1 表示具体。值得注意的是,ValueErrorException 实例将包含更多信息,viz.“invalid literal for int() with base 10: 'abcd'”。
    • 只是想提一下...如果您要转换的变量有可能是None,那么您将希望您的 except 块为except (TypeError, ValueError):
    【解决方案2】:

    这里是:

    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
    

    【讨论】:

    • -1 用于捕获几乎所有可能的异常,而不仅仅是ValueError。你应该只抓住你知道如何处理的东西。
    • 捕获比你需要的更多是非常不好的做法。调整你的答案,我很乐意改变我的投票。
    • +1 这只是一个示例,因此显示捕获 ValueError 和其他类型异常的模式非常具有指导意义。例如解析参数并在无效或未定义时设置默认值非常有用。
    • 我碰巧在一个非常大的 Python 代码库上工作,该代码库左右抛出了大量异常。在某一时刻,除了捕获所有问题之外别无他法——你不知道上周在不同国家工作的不同团队的成员在你的代码下方 10 层添加了什么新异常。来自 c++ 我会说 python 中的异常被过度使用了。
    【解决方案3】:

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

    要在 Python 中将字符串 (or any other type that can be converted) 转换为整数,只需调用 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'
    

    在 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'
    

    【讨论】:

    【解决方案4】:

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

    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
    

    【讨论】:

      【解决方案5】:

      你可以这样做:

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

      【讨论】:

      • 你的 except 语句的语法是错误的——它永远不会捕获任何东西。使用except (type1, type2): 语法捕获多个异常。将特定错误与通用基类 Exception 结合起来毫无意义。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      • 2018-11-07
      • 2011-04-28
      • 2013-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多