【问题标题】:Check if input consists of a comma-separated list of numbers [duplicate]检查输入是否由逗号分隔的数字列表组成[重复]
【发布时间】:2020-12-28 01:46:40
【问题描述】:

如果用户以不正确的方式输入输入,我想构建一个 while 循环,它表示输入无效,然后重试。用户的输入应该是用逗号分隔的数字,然后它将存储在一个列表中。输入如下:

number = input("input your number? (separated by comma): ")
number_list = number.split(',')
numbers = [int(x.strip()) for x in number_list]
print(numbers)

但问题我不知道如何检查输入是否是用逗号分隔的数字。 因此,例如,如果用户输入 0,1,它将存储在 [0,1] 之类的列表中。当用户输入除数字以外的任何内容时,它应该要求用户提供正确的输入。

理想的代码应该是这样的:

# Start a loop that will run until the user a give valid input.
while numbers != 'List of Numbers separated by comma':
   # Ask user for input.
   number = input("input your number? (separated by comma): ")
   number_list = number.split(',')
   numbers = [int(x.strip()) for x in number_list]

   # Add the new name to our list.
   if numbers == 'List of Numbers separated by comma':
       print(numbers)
   else:
       print('Gave an incorrect input, please try again')

感谢您的帮助。

【问题讨论】:

  • 当输入 isn't 符合时,您现有的代码不会抛出异常吗?您是否考虑过处理该异常?

标签: python input while-loop


【解决方案1】:

您可以使用正则表达式来查找值,以便只接受某些字符。

import re

pattern = re.compile(r"^[0-9\,]*$")
print(pattern.findall("z")
print(pattern.findall("1,2,3,4")

>> []
>> [1,2,3,4]

分解^[0-9\,]*$

^ - 字符串开始

[ ... ] - 括号中的字符之一

0-9 - 0 到 9 之间的任意数字

\, - 包括逗号,其中\ 转义特殊的逗号字符

* - 零个或多个

$ - 字符串结束

【讨论】:

    【解决方案2】:

    改编自 Trenton McKinney 标记的副本。

    请尝试更多测试用例,以防我错了

    对于我所尝试的,我得到了结果输出。

    while True:
        test=input("Nums sep by comma: ")
        test_list = test.split(',')
        try:
            numbers = [int(x.strip()) for x in test_list]
        except:
            print('please try again, with only numbers separated by commas (e.g. "1, 5, 3")')
            continue
        else:
            print(numbers)
            break
    print(numbers)
    

    测试

    Nums sep by comma: 1, asdf
    please try again, with only numbers separated by commas (e.g. "1, 5, 3")
    Nums sep by comma: 1, 2, 5
    [1, 2, 5]
            
    

    【讨论】:

    • 这是对副本的改编,但我投票结束这个问题。
    • 不知道adaptation from the duplicate是什么但感觉不错
    • 也许我应该写 “改编自 Trenton 标记为重复的问题中给出的最佳答案”,但你会开玩笑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 2022-06-10
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    相关资源
    最近更新 更多