【问题标题】:What is the best way to restrain user input to only wanted characters将用户输入限制为只需要字符的最佳方法是什么
【发布时间】:2018-09-18 17:55:03
【问题描述】:

我希望用户不能写除 'y' 和 'n' 以外的字符 我读过很多资料,但似乎都没有解释这种情况。

ready = raw_input('\nOK, Ready? (y/n)\n')

【问题讨论】:

  • if ready.lower() in {'ok', 'y', 'yes'}:(这也接受YESYes等)。

标签: python python-2.7 input


【解决方案1】:

这是一种您可以重复请求输入直到输入位于提供的set 中的方法:

ready = ''

while ready not in {'y', 'n'}:
    ready = raw_input('\nOK, Ready? (y/n)\n')

print('Success')

注意字符串区分大小写。使用str.lower 表示不区分大小写。

也相关:Asking the user for input until they give a valid response

【讨论】:

    猜你喜欢
    • 2020-11-20
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多