繁体   English   中英

Python:检查字符串是否在列表中,否则抛出错误

[英]Python: Check if string is in list otherwise throw error

我想检查字符串s是否在给定列表中valid_string 如果没有,我想抛出一个错误。

valid_string = ['abc', 'def', 'ghi']
s = 'test'
if s not in valid_string:
# Throw error: ('"{}" is not a valid string. Valid strings are {}'.format(s, valid_string))

抛出错误的最佳实践是什么?

您可以尝试使用“手动异常”,如下所示:

valid_string = ['abc', 'def', 'ghi']
s = 'test'
if s not in valid_string:
    raise Exception('This is the exception you expect to handle')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM