Python输入验证

时间:2012-04-03 19:43:58

标签: python input validation

我有一个菜单会返回'e',除非输入是d或D. 我想这样做而不需要另外一个变量并在一行上完成

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]

2 个答案:

答案 0 :(得分:3)

使用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):"))

虽然,这显然有点迟钝而且太“聪明”了一半。

答案 1 :(得分:1)

并不是真正意义上的另一种解决方案(我不认为它是可读的):

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

至少它很短。有时字典实际上对类似情况有用(如果有更多选择)。