约束输入长度pythonsys.stdin.readline()
Constraint input length python sys.stdin.readline()
我尝试解决来自this website的算法问题!问题是所有的问题都得靠系统输入来实现。
所以我会用
from stdin import sys
a = stdin.readline()
# do something
我的问题是有时我需要像下面那样做。
第一行是整数 n
(1n 长度的字符串或数字,其中有 n
个数字。
举个例子
输入
4
1100
问题是如何限制匹配 4 位数字(长度) 的第二行作为输入。如何?为什么?
您不能以这种方式限制输入长度。
正如@Andrey 建议的那样,您应该阅读输入,如果不正确,打印错误并阅读新的输入。
顺便说一句 reading input in python 3 的 pythonic 方式是:
a = input("prompt")
所以你可以这样做:
a = ""
while len(a) != 4:
a = input("please enter a 4 digit number: ")
我尝试解决来自this website的算法问题!问题是所有的问题都得靠系统输入来实现。
所以我会用
from stdin import sys
a = stdin.readline()
# do something
我的问题是有时我需要像下面那样做。
第一行是整数 n
(1n 长度的字符串或数字,其中有 n
个数字。
举个例子
输入
4
1100
问题是如何限制匹配 4 位数字(长度) 的第二行作为输入。如何?为什么?
您不能以这种方式限制输入长度。
正如@Andrey 建议的那样,您应该阅读输入,如果不正确,打印错误并阅读新的输入。
顺便说一句 reading input in python 3 的 pythonic 方式是:
a = input("prompt")
所以你可以这样做:
a = ""
while len(a) != 4:
a = input("please enter a 4 digit number: ")