在同一行连续输入

  • 本文关键字:一行 连续 python input
  • 更新时间 :
  • 英文 :


我做了一个循环,让用户输入数字,直到他输入"13",然后循环就会中断。

while True:
number = int(input())
if number == 13:
print("goodbye")
break

当我运行这个程序时,它看起来像这样:

1
2
3
13
goodbye

但每当我按下回车键时,我希望输入继续在同一行中,如下所示:

1 2 3 13
goodbye

我该怎么做?

一种相对简单的方法是:

import os
prompt = ''
while True:
number = input(prompt)
os.system('cls')
# prompt += number + ' ' #If you want the control input to be printed, keep this, remove the other
if int(number) == 13:
print(prompt)
print('goodbye')
break
prompt += number + ' '    # add this line before the if starts, if you want to keep 13
os.system('cls')

输出:

1 2 3 4
goodbye

注意,这并没有按照您在注释中想要的方式打印13。但是,如果要保留它,可以在if条件开始之前将其移动到行中。

这在Windows命令提示符下工作,不能保证不同的IDLE/iPython等

注意:这将清除控制台中的所有行,并重写它们。这适用于您的特定问题,但如果以前也打印过其他内容,则可能不理想。如果你想避免这种情况,你必须在点击这部分代码之前将sys.stdout重定向到一个文件或某种字符串缓冲区,然后恢复stdout,并将缓冲区的内容作为文本存储在上面使用的prompt变量中。

您需要一些东西,可以让您一次读取一个字符,而无需等待换行符。这个问题提供了许多解决方案。我在这里做了一个使用getch包装器的小例子,它应该是非常跨平台的(可以通过pip或类似程序安装(:

from sys import stdout
from getch import getch
lines = []
line = []
while True:
k = getch()
if k == 'n':
item = ''.join(line)
line.clear()
lines.append(item)
try:
if int(item) == 13:
stdout.write(k)
break
except ValueError:
pass
stdout.write(' ')
else:
stdout.write(k)
line.append(k)
stdout.flush()
print('goodbye!')
print(lines)

虽然这不会有像开箱即用的工作退格这样的功能,但它可以为正确的输入做你想要的事情,你可能可以实现它们。以下是输入asdfn48484n13n:的运行示例

asdf 48484 13
goodbye!
['asdf', '48484', '13']

这是可能的,但解决方案取决于系统。这应该适用于windows 10,但有可能你必须更改它的一些设置(现在我不知道哪个编辑:此设置(。诀窍是使用ansi控制字符,用于更改控制台:

import sys
UP_ONE_LINE = "33[A" # up 1 line
DELETE_LINE = "33[K" # clear line 
number = []
while True:
#number = int(input())
number.append(int(input()))
sys.stdout.write(UP_ONE_LINE)
sys.stdout.write(DELETE_LINE)
print(number,end="")
if number[-1] == 13:
print("ngoodbye")
break

它删除最后一行,然后写入所有数字。你也可以使用控制字符到最后一行的末尾,但这些都是我使用的。在我的控制台中,结果是:

[1, 2, 3, 4, 13]
goodbye

Python使用空格键从输入继续

import sys
import getch
input = ""
while True:
key = ord(getch.getch())
sys.stdout.write(chr(key))
sys.stdout.flush()
# If the key is space
if  key != 32:
input += chr(key)
else:
input =   ""
if input == "13":
print("nbye")
break

最新更新