How do you print inputs in one line in python?

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"
h2 = input[]
print "pears."

Should be modified as to output to the console in one line saying:

I have h apples and h2 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.

jherran

3,2498 gold badges35 silver badges50 bronze badges

asked May 9, 2015 at 16:01

1

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.

answered May 9, 2015 at 16:05

WouterWouter

1,5387 gold badges30 silver badges35 bronze badges

3

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 python2.x or python3.x, so here's a python3.x answer as well.

print["I have {0} apples and {1} pears".format[input[], input[]]]

answered May 9, 2015 at 16:19

Ethan BierleinEthan Bierlein

3,2034 gold badges27 silver badges41 bronze badges

0

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 //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."]

answered Jun 6, 2016 at 9:25

1

How do you print an input on the same line in Python?

To print on the same line in Python, add a second argument, end=' ', to the print[] function call.

How do you print multiple items on one line Python?

To print multiple expressions to the same line, you can end the print statement in Python 2 with a comma [ , ]. You can set the end argument to a whitespace character string to print to the same line in Python 3.

How do you take a list of inputs in one line in Python?

To take list input in Python in a single line use input[] function and split[] function. Where input[] function accepts a string, integer, and character input from a user and split[] function to split an input string by space.

How do you get two inputs on the same line in Python?

Using Split [] Function With the help of the split [] function, developers can easily collect multiple inputs in Python from the user and assign all the inputs to the respective variables.

Chủ Đề