[英]Python Input validation
我有一個菜單,除非輸入是 d 或 D,否則它將返回“e”。我想在不創建另一個變量並在一行上執行它的情況下執行此操作
encrypt = 'd' if (raw_input("Encrypt or Decrypt a file(E/d):") == ('d' or 'D')) else 'e'
[編輯] 好的,這是一個更難的
我該怎么做
file_text = 'a.txt' if (raw_input("File name(a.txt):")=='a.txt' else [What I typed in]
使用in
運算符:
encrypt = 'd' if raw_input("Encrypt or decrypt a file (E/d):") in ('d', 'D') else 'e'
或者,您可以將輸入轉換為小寫並將其與“d”進行比較:
encrypt = 'd' if raw_input("Encrypt or decrypt a file (E/d):").lower() == 'd' else 'e'
最后,如果你想確保他們輸入的是 e 或 d,你可以將其包裝在一個 while 循環中:
while True:
encrypt = raw_input("Encrypt or decrypt a file (E/d):")
# Convert to lowercase
encrypt = encrypt.lower()
# If it's e or d then break out of the loop
if encrypt in ('e', 'd'):
break
# Otherwise, it'll loop back and ask them to input again
編輯:要回答你的第二個問題,我猜你可以使用 lambda 嗎?
file_text = (lambda default, inp: default if inp.lower() == default else inp)("a.txt", raw_input("File name(a.txt):"))
雖然,這顯然有些遲鈍,也太“聰明”了一半。
不是真的認真,而是另一個單行解決方案(我認為它不可讀):
encrypt = {'d':'d','D':'d'}.get(raw_input("Encrypt or decrypt a file (E/d):"), 'e')
至少它很短。 有時字典實際上對類似的情況很有用(如果有更多選擇的話)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.