【问题标题】:Python: "Print" and "Input" in one line [duplicate]Python:一行中的“打印”和“输入”[重复]
【发布时间】:2015-07-20 10:45:54
【问题描述】:

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

例如:

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

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

I have h apples and h1 pears.

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

【问题讨论】:

  • @jherran 请从帖子中删除<br>,因为它们不是必需的。

标签: python input printing line


【解决方案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.")

【讨论】:

  • 这个答案相当缺乏功能(除了通过退格键、键盘中断、粘贴和行历史记录外,没有向前删除、导航)。提供了更好的答案here 和(这里)[stackoverflow.com/a/41459565/6379747]。后者是这里答案的过度设计版本。
【解决方案2】:

您可以执行以下操作:

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.

逗号符号阻止了打印语句后的新行,但输入后的返回仍然存在。

【讨论】:

  • 谢谢,我不知道格式化也可以像输入一样工作。
  • 但是,文本仅在我输入两个数字后才会出现 - 但是,它应该出现在数字之前,例如“我有” - 然后输入数字,从而继续文本。抱歉,我没有提到:我有 Python 2.7。
  • @Yinyue 查看更新的答案。
【解决方案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()))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 2020-05-14
    相关资源
    最近更新 更多