如何解决如何限制python的input函数的输入参数数量?
假设我有这个:
maxNumOfArgs = int(input("enter length of list: "))
listOfNums = input("enter space separated list elements: ")
没有什么能阻止用户输入超过maxNumOfArgs
的参数。是否有一种简洁,pythonic的方式来限制input()
调用中输入的参数的数量?
解决方法
拆分str
返回的input()
时,可以通过传递参数maxsplit
来限制拆分次数。
示例:
>>> test = input("enter data: ")
a b c d e f
>>> args = test.split(" ",maxsplit=3)
>>> args
['a','b','c','d e f']
请注意,在最坏的情况下,由于将split限制为3个split,因此split返回的数组将包含4个元素。
,分割第二个输入字符串时,可以剥离超出请求的最大长度的所有参数
# 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]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。