Python:一行代码中的“Print”和“Input”

4
如果我想在python中的文本中插入一些输入,如何做到在用户输入并按下回车键之后不换行?
例如:
print "I have"
h = input()
print "apples and"
h1 = input()
print "pears."

需要修改代码,使得输出结果在控制台上一行内显示:

I have h apples and h1 pears.

这一行必须在同一行上没有更深层次的目的,这只是假设,我希望它看起来像这样。


@jherran,请从帖子中删除<br>,因为它们是不必要的。 - Ethan Bierlein
3个回答

7
你可以执行以下操作:
print 'I have %s apples and %s pears.'%(input(),input())

基本上,您有一个字符串,其中包含两个输入。

编辑:

据我所知,要使两个输入都在一行上不是(容易)实现的。最接近的方法是:

print 'I have',
a=input()
print 'apples and',
p=input()
print 'pears.'

这将输出:

I have 23
apples and 42
pears.

逗号符号可以避免在print语句后换行,但在输入后的回车仍然存在。

谢谢,我不知道格式化在输入方面也能这样工作。 - Yinyue
然而,文本只有在我输入两个数字后才会出现 - 它应该出现到数字,例如“我有” - 然后输入数字,继续文本。抱歉我没有提到:我使用的是Python 2.7。 - Yinyue
@Yinyue,请查看更新后的答案。 - Wouter

3
虽然其他答案是正确的,但是 % 已经废弃了,应该使用字符串 .format() 方法。以下是您可以使用的方法。
print "I have {0} apples and {1} pears".format(raw_input(), raw_input())

此外,从您的问题中无法确定您是否使用 还是 ,因此这里也提供一个 的答案。
print("I have {0} apples and {1} pears".format(input(), input()))

1
如果我理解正确,你想做的是在获取输入时不回显换行符。如果你使用的是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.")

这个答案的功能相当不足(没有前向删除、导航除了通过退格键、KeyboardInterrupts、粘贴和行历史记录)。更好的答案在这里这里提供。后者是这个答案的过度设计版本。 - ForgottenUmbrella

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接