Python: "Print" 和 "Input" 在一行

Python: "Print" and "Input" in one line

如果我想在 python 中的文本之间输入一些内容,如果不在用户输入内容并按下回车键后切换到新行,我该怎么做?

例如:

print "I have"
h = input()
print "apples and"
h1 = input()
print "pears."

应该修改为一行输出到控制台说:

I have h apples and h1 pears.

事实上它应该在一条线上没有更深层次的目的,它是假设的,我希望它看起来像那样。

您可以执行以下操作:

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 语句后换行,但输入后的 return 仍然存在。

虽然另一个答案是正确的,但 % 已被弃用,应改用字符串 .format() 方法。以下是您可以改为执行的操作。

print "I have {0} apples and {1} pears".format(raw_input(), raw_input())

另外,从你的问题来看,你是否也在使用 or , so here's a 答案并不清楚。

print("I have {0} apples and {1} pears".format(input(), input()))

如果我没理解错的话,你想要做的是在不回显换行符的情况下获取输入。如果您使用的是 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.")