Python:一行中的“打印”和“输入”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30142107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: "Print" and "Input" in one line
提问by Yinyue
If I'd like to put some input in between a text in python, how can I do it without, after the user has input something and pressed enter, switching to a new line?
如果我想在 python 中的文本之间输入一些输入,在用户输入内容并按下 Enter 后,我怎么能不切换到新行呢?
E.g.:
例如:
print "I have"
h = input()
print "apples and"
h1 = input()
print "pears."
Should be modified as to output to the console in one line saying:
应该修改为在一行中输出到控制台说:
I have h apples and h1 pears.
The fact that it should be on one line has no deeper purpose, it is hypothetical and I'd like it to look that way.
它应该在一条线上这一事实没有更深层次的目的,它是假设性的,我希望它看起来如此。
采纳答案by ForgottenUmbrella
If I understand correctly, what you are trying to do is get input without echoing the newline. If you are using Windows, you could use the msvcrt module's getwch method to get individual characters for input without printing anything (including newlines), then print the character if it isn't a newline character. Otherwise, you would need to define a getch function:
如果我理解正确,您要做的是在不回显换行符的情况下获取输入。如果您使用的是 Windows,您可以使用 msvcrt 模块的 getwch 方法来获取输入的单个字符而不打印任何内容(包括换行符),然后打印该字符(如果它不是换行符)。否则,您需要定义一个 getch 函数:
import sys
try:
from msvcrt import getwch as getch
except ImportError:
def getch():
"""Stolen from http://code.activestate.com/recipes/134892/"""
import tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def input_():
"""Print and return input without echoing newline."""
response = ""
while True:
c = getch()
if c == "\b" and len(response) > 0:
# Backspaces don't delete already printed text with getch()
# "\b" is returned by getch() when Backspace key is pressed
response = response[:-1]
sys.stdout.write("\b \b")
elif c not in ["\r", "\b"]:
# Likewise "\r" is returned by the Enter key
response += c
sys.stdout.write(c)
elif c == "\r":
break
sys.stdout.flush()
return response
def print_(*args, sep=" ", end="\n"):
"""Print stuff on the same line."""
for arg in args:
if arg == inp:
input_()
else:
sys.stdout.write(arg)
sys.stdout.write(sep)
sys.stdout.flush()
sys.stdout.write(end)
sys.stdout.flush()
inp = None # Sentinel to check for whether arg is a string or a request for input
print_("I have", inp, "apples and", inp, "pears.")
回答by Wouter
You can do following:
您可以执行以下操作:
print 'I have %s apples and %s pears.'%(input(),input())
Basically you have one string that you formant with two inputs.
基本上你有一个用两个输入共振峰的字符串。
Edit:
编辑:
To get everything on one line with two inputs is not (easily) achievable, as far as I know. The closest you can get is:
据我所知,通过两个输入将所有内容都放在一条线上并不是(容易)实现的。你能得到的最接近的是:
print 'I have',
a=input()
print 'apples and',
p=input()
print 'pears.'
Which will output:
这将输出:
I have 23
apples and 42
pears.
The comma notation prevents the new line after the print statement, but the return after the input is still there though.
逗号符号阻止了打印语句后的新行,但输入后的返回仍然存在。
回答by Ethan Bierlein
While the other answer is correct, the %
is deprecated, and the string .format()
method should be used instead. Here's what you could do instead.
虽然另一个答案是正确的,但%
已弃用,.format()
应改用string方法。这是你可以做的。
print "I have {0} apples and {1} pears".format(raw_input(), raw_input())
Also, from your question it's not clear as to whether you're using python2.xor python3.x, so here's a python3.xanswer as well.
另外,根据您的问题,不清楚您使用的是python2.x还是python3.x,所以这里也有一个python3.x答案。
print("I have {0} apples and {1} pears".format(input(), input()))