Python: “Print” and “Input” in one line [duplicate

2019-06-24 17:19发布

This question already has an answer here:

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?

E.g.:

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.

3条回答
手持菜刀,她持情操
2楼-- · 2019-06-24 17:31

While the other answer is correct, the % is deprecated, and the string .format() method should be used instead. Here's what you could do instead.

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

Also, from your question it's not clear as to whether you're using or , so here's a answer as well.

print("I have {0} apples and {1} pears".format(input(), input()))
查看更多
聊天终结者
3楼-- · 2019-06-24 17:37

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 == "\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.")
查看更多
女痞
4楼-- · 2019-06-24 17:37

You can do following:

print 'I have %s apples and %s pears.'%(input(),input())

Basically you have one string that you formant with two inputs.

Edit:

To get everything on one line with two inputs is not (easily) achievable, as far as I know. The closest you can get is:

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

Which will output:

I have 23
apples and 42
pears.

The comma notation prevents the new line after the print statement, but the return after the input is still there though.

查看更多
登录 后发表回答