繁体   English   中英

“ValueError: '' is not in list”作为错误给出,而不是在 elif 语句中继续

[英]"ValueError: '' is not in list" is given as an error instead of just moving on in an elif statement

所以我目前正在用 Python 编写一个简单的脚本来处理 ROT13 密码。 我写了一小段代码,理论上应该检查给定的字母是大写还是小写,或者不在字母表中,例如标点符号。 但是,如果我给它输入一个字符,例如一个不在字母表中的空格或感叹号,它会抛出一个 Value 错误,并说它不在我的 elif 语句中引用的列表中,而不仅仅是运行 else 语句. 如果字符不在字母表中,我该怎么做才不会破坏程序? 谢谢。

作为参考,plain_alphabet 和 cipher_alphabet 只是包含字母表中每个字母的列表。 我知道它效率低下,但到目前为止它有效。

message 也只是一个字符串。

for x in message:
    if x in plain_alphabet:
        message_list.append(cipher_alphabet[plain_alphabet.index(x)])
    elif x in [x.upper() for y in plain_alphabet]:
        message_list.append((cipher_alphabet[plain_alphabet.index(x.lower())]).upper())
    else:
        message_list.append(x)
print(''.join(message_list))

user10987432 是对的, elif x in [x.upper() for y in plain_alphabet]:应该是elif x in [**y**.upper() for y in plain_alphabet]:

暂无
暂无

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

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