本文介绍了Python:“打印"和“输入"一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

例如:

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.

推荐答案

如果我理解正确,您尝试做的是在不回显换行符的情况下获取输入.如果您使用的是 Windows,您可以使用 msvcrt 模块的 getwch 方法来获取单个字符以供输入而不打印任何内容(包括换行符),然后打印该字符(如果它不是换行符).否则,您需要定义一个 getch 函数:

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:

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 == "" and len(response) > 0:
            # Backspaces don't delete already printed text with getch()
            # "" is returned by getch() when Backspace key is pressed
            response = response[:-1]
            sys.stdout.write(" ")
        elif c not in ["
", ""]:
            # Likewise "
" is returned by the Enter key
            response += c
            sys.stdout.write(c)
        elif c == "
":
            break
        sys.stdout.flush()
    return response


def print_(*args, sep=" ", end="
"):
    """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.")

这篇关于Python:“打印"和“输入"一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 13:08