【问题标题】:how to check if raw_input contains 3 digits?如何检查 raw_input 是否包含 3 位数字?
【发布时间】:2014-08-28 17:24:37
【问题描述】:

我是初学者,需要一些帮助。我怎样才能确保用户的输入只有 3 位数字。我知道如何确定它是否是数字,但只需要 3。这就是我到目前为止所拥有的:

while not (area_code.isdigit()):
    # do something here

我希望“.isdigit()”为 3 位数。

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    您还需要明确测试字符串的长度:

    while not (area_code.isdigit() and len(area_code) == 3):
    

    str.isdigit() 只有在至少有一个字符且所有字符都是数字时才为真。那么剩下的就是对长度的测试了。

    【讨论】:

    • 你的逻辑正确吗?不应该是while (area_code.isdigit() and len(area_code) == 3)
    • @PadraicCunningham:不,while 循环应该继续,直到找到正确的area_code。 OP 有while not area_code.isdigit(),我只是添加了长度要求。
    • 但是如果while not area_code.isdigit() and len(area_code) == 3) 没有在循环内定义,它如何永远循环?
    • @PadraicCunningham:你忘记了( 的开场白。 while 循环的主体在这里完全脱离上下文,但如果主体中的area_code = '123' 将结束循环。
    【解决方案2】:
    while True:
        inp = raw_input()
        if len(inp) == 3 and inp.isdigit():
            break
    

    如果你想接受多个输入,你需要在你的循环中接受输入

    使用您的示例:

    area_code = raw_input()
    while len(area_code) != 3 or not area_code.isdigit():
        area_code = raw_input()
    

    【讨论】:

      【解决方案3】:
      while not len(area_code) == 3:
          # Do stuff
      

      【讨论】:

        猜你喜欢
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 2012-09-14
        • 2013-12-17
        • 1970-01-01
        • 2012-08-30
        • 2022-11-30
        • 1970-01-01
        相关资源
        最近更新 更多