【问题标题】:How to print the value only which is creating exception in python?如何仅打印在python中创建异常的值?
【发布时间】:2020-10-18 00:12:57
【问题描述】:
try:
    a,b = map(int,input().split())
    print(a//b)
except ZeroDivisionError:
    print("invalid")
except ValueError:
    print("this value _ is not allowed for division")

我需要在此处打印值 _ 这是由“#”或“%”等异常引起的

【问题讨论】:

  • 你能否更详细地描述问题我在理解发生了什么时遇到了问题。

标签: python-3.x exception valueerror


【解决方案1】:

看起来您正在尝试获得类似于下面显示的代码的内容。这可以通过使用正则表达式(通过re 模块的search() 函数)来查找异常(e)参数(args)中出现的无效参数。

e.args 是一个元组,当 ValueError 由于输入的无效输入而引发时,该元组如下所示:

("invalid literal for int() with base 10: '%'",)

因此,我们可以这样做:

import re


try:
    a, b = map(int, input().split())
    print(a // b)
except ZeroDivisionError:
    print("Can't divide by zero")
except ValueError as e:
    regex_groups = re.search('\'(.+)\'|\"(.+)\"', e.args[0]).groups()
    invalid_arg = regex_groups[0] if regex_groups[0] else regex_groups[1]
    print(f"This value: {invalid_arg} is not allowed for division")

测试:

1 $
This value: $ is not allowed for division
Q 2
This value: Q is not allowed for division
% '
This value: % is not allowed for division
20 ?
This value: ? is not allowed for division
50 2
25

【讨论】:

    猜你喜欢
    • 2010-12-01
    • 2017-05-26
    • 2017-12-21
    • 2011-01-27
    • 2013-02-24
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多