如果我使用 raw_input() ,它将获取所有用户输入。我想在用户输入“-1”时停止接受输入。
我的意思是,如果用户输入“12 22 -23 3 -1 23 -1 23”,则不应在 3 之后读取。
任何其他读取输入的方式也可以。
最佳答案
... The sequence never stops. Example: 1 2 -1 2 -3 -1 34 12 ...................... it never stops. But I have to stop reading if I encounter -1.
raw_input()
始终读取整行。
如果您不想阅读整行;你可以尝试 sys.stdin.read(1)
来代替:
import sys
def read_until_minus_one():
buf = []
seen_minus = False
while True:
char = sys.stdin.read(1)
if not char: # EOF
break
if char == '1' and seen_minus:
buf.pop() # chop the last minus
break # seen -1
else:
seen_minus = (char == '-')
buf.append(char)
return ''.join(buf)
print(read_until_minus_one())
Example
12 22 -23 13 -12 23 -1 23 12
输出
12 22 -23 13
注意:一旦读取到-1
,它就会停止。在这种情况下,后续的 sys.stdin.read(1)
返回 '2'
。
如果您只想在遇到 -1
作为空格分隔的标记(而不是像 -12
中那样作为数字的一部分)时停止,则输入解析可以分为两个阶段:
- 将输入拆分为空格分隔的标记
- 获取 token ,直到遇到
-1
#!/usr/bin/env python
import sys
from functools import partial
from itertools import takewhile
def get_tokens(stream=sys.stdin):
token = []
for char in iter(partial(stream.read, 1), ''):
if char.isspace(): # use any space as a separator
if token:
yield ''.join(token)
del token[:]
else:
token.append(char)
if token:
yield ''.join(token)
print(' '.join(takewhile(lambda s: s != '-1', get_tokens())))
Output
12 22 -23 13 -12 23
注意:在这种情况下它会读取更多内容,因为在这种情况下 -12
内部无法识别 -1
。
注意:您不需要 curses
或 other means of reading a single character from the user in this case 。仅当输入是交互式的并且您希望在用户按 Enter(或 EOF)之前获取内容时才需要它。
sys.stdin
默认情况下进行缓冲。因此 .read(1)
可能会在内部读取多个字符。如果我们(可能)是流的唯一使用者,那么这并不重要,因为从我们的末尾 .read(1)
总是一次返回一个字符。
关于python - 如何在Python中使用raw_input()在特定字符之后停止读取用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28780698/