简体   繁体   English

Python 输入验证

[英]Python Input validation

I have a menu that will return 'e' unless the input is d or D. I would like to do it without making another variable and doing it on one line我有一个菜单,除非输入是 d 或 D,否则它将返回“e”。我想在不创建另一个变量并在一行上执行它的情况下执行此操作

encrypt = 'd' if (raw_input("Encrypt or Decrypt a file(E/d):") == ('d' or 'D')) else 'e'

[Edit] Ok here is a harder one [编辑] 好的,这是一个更难的

How can I do the same for this我该怎么做

file_text = 'a.txt' if (raw_input("File name(a.txt):")=='a.txt' else [What I typed in]

Use the in operator:使用in运算符:

encrypt = 'd' if raw_input("Encrypt or decrypt a file (E/d):") in ('d', 'D') else 'e'

Alternatively, you can just convert the input to lowercase and compare it to 'd':或者,您可以将输入转换为小写并将其与“d”进行比较:

encrypt = 'd' if raw_input("Encrypt or decrypt a file (E/d):").lower() == 'd' else 'e'

Finally, if you want to ensure that they enter e or d, you can wrap it up in a while loop:最后,如果你想确保他们输入的是 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

Edit: To answer your second question, you can use a lambda for it I guess?编辑:要回答你的第二个问题,我猜你可以使用 lambda 吗?

file_text = (lambda default, inp: default if inp.lower() == default else inp)("a.txt", raw_input("File name(a.txt):"))

Although, this is clearly a bit obtuse and too "clever" by half.虽然,这显然有些迟钝,也太“聪明”了一半。

Not really meant seriously but another 1-line solution (I don't think it's readable):不是真的认真,而是另一个单行解决方案(我认为它不可读):

encrypt = {'d':'d','D':'d'}.get(raw_input("Encrypt or decrypt a file (E/d):"), 'e')

At least it's short.至少它很短。 Sometimes a dictionary is actually useful for similar situations (if there are more choices).有时字典实际上对类似的情况很有用(如果有更多选择的话)。

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

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