[英]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.