加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python:“打印”和“输入”在一行

发布时间:2020-12-20 11:42:49 所属栏目:Python 来源:网络整理
导读:参见英文答案 Possible to get user input without inserting a new line?????????????????????????????????????7个 如果我想在python中的文本之间添加一些输入,我怎么能在没有用户输入内容并按下回车后切换到新行? 例如.: print "I have"h = input()print
参见英文答案 > Possible to get user input without inserting a new line?????????????????????????????????????7个
如果我想在python中的文本之间添加一些输入,我怎么能在没有用户输入内容并按下回车后切换到新行?

例如.:

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

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

I have h apples and h1 pears.

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

解决方法

如果我理解正确,你要做的是获得输入而不回应换行符.如果您使用的是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","pears.")

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读