在Python中比较'clienterror'和'string'

2024-10-08 21:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将clienterror消息的输出与python中的字符串进行比较,但无法使其正常工作。 这可能吗

我尝试了三种方法来解决这个问题:(A)(我没有得到任何结果)

    except ClientError as e:
    a = "An error occurred (ValidationError) when calling the UpdateStack operation: Stack [name] does not exist"
    b = "An error occurred (ValidationError) when calling the UpdateStack operation: No updates are to be performed."
    if e is a:
        print ('Stack [name] does not exist')
    if e == b:
        print ('No updates are to be performed')

(B)

print e[5]
IndexError: tuple index out of range
--
    print (e[76:])
()
    print (e[:-1])
()

(C) 我试着通过跑步来理解这个句子有多少部分

        print (len(e))

但是我得到了“TypeError:ClientError类型的对象没有len()

所以。。。我真的不能将ClientError与字符串进行比较吗


Tags: the字符串nameanstackerroroperationwhen
1条回答
网友
1楼 · 发布于 2024-10-08 21:17:24

不,不能将字符串与异常进行比较。它们不是同一类型的is仅当它们是同一对象时才会返回true。即使==在这里也不起作用,因为如上所述,它们不是同一类型

但是,您可以将异常强制转换为字符串,然后使用in查看它是否包含以下消息:

ex_str = str(e)
a = "does not exist"

if a in ex_str:
    print ('Stack [name] does not exist')

只有当str(e)包含完整的错误消息时,in检查才会起作用。如果没有,你需要以另一种方式获得信息。异常消息的处理方式取决于子类,我无权访问要测试的ClientError对象;我在网上也找不到它的定义

相关问题 更多 >

    热门问题