如何限制 python 的 input() 函数的输入参数数量?
How do you limit the number of input arguments for python's input() function?
假设我有这个:
maxNumOfArgs = int(input("enter length of list: "))
listOfNums = input("enter space separated list elements: ")
没有什么能阻止用户输入比 maxNumOfArgs
更多的参数。是否有一种简洁的 pythonic 方法来限制 input()
调用中输入的参数数量?
拆分input()
返回的str
时,可以通过参数maxsplit
.
限制拆分次数
示例:
>>> test = input("enter data: ")
a b c d e f
>>> args = test.split(" ", maxsplit=3)
>>> args
['a', 'b', 'c', 'd e f']
请注意,在最坏的情况下,split 返回的数组将包含 4 个元素,因为您将其限制为 3 次拆分。
当您拆分第二个输入字符串时,您可以去除超出请求的最大长度的任何参数
# Get requested length
max_num_args = int(input("enter length of list: "))
# Get input string of comma-separated elements
all_inputs = input("enter space separated list elements: ")
# Split string by comma and only keep up to the maximum requested list length
input_values = all_inputs.split(',')[:max_num_args]
假设我有这个:
maxNumOfArgs = int(input("enter length of list: "))
listOfNums = input("enter space separated list elements: ")
没有什么能阻止用户输入比 maxNumOfArgs
更多的参数。是否有一种简洁的 pythonic 方法来限制 input()
调用中输入的参数数量?
拆分input()
返回的str
时,可以通过参数maxsplit
.
示例:
>>> test = input("enter data: ")
a b c d e f
>>> args = test.split(" ", maxsplit=3)
>>> args
['a', 'b', 'c', 'd e f']
请注意,在最坏的情况下,split 返回的数组将包含 4 个元素,因为您将其限制为 3 次拆分。
当您拆分第二个输入字符串时,您可以去除超出请求的最大长度的任何参数
# Get requested length
max_num_args = int(input("enter length of list: "))
# Get input string of comma-separated elements
all_inputs = input("enter space separated list elements: ")
# Split string by comma and only keep up to the maximum requested list length
input_values = all_inputs.split(',')[:max_num_args]