Singularity
Singularity

Reputation: 15

How to print text after input on the same line

I'm wondering if there is a way to be able to print a statement after the input on the same line.

Like how print() has 'end=', but input does not...

user = input("Type Here: ")
print("Text")

# -- Output:
# Type Here: input_here
# text_here

# -- Wanted Output:
# Type Here: input_here text_here

Upvotes: 0

Views: 134

Answers (3)

blhsing
blhsing

Reputation: 106553

You can create your own version of the input function by getting keystrokes silently with the msvcrt.getch function in a loop. With each keystroke, you either append it to a list and output it to the console, or abort the loop if it's a carriage return.

To deal with a backspace, pop the last character from the list and output a backspace, then a space to erase the last character from the console, and then another backspace to actually move the cursor backwards.

Note that msvcrt.getch works only in Windows, and you should install the getch package instead in other platforms:

try:
    from msvcrt import getch
except ModuleNotFoundError:
    from getch import getch

def input_no_newline(prompt=''):
    chars = []
    print(prompt, end='', flush=True)
    while True:
        char = getch().decode()
        if char == '\r':
            break
        if char != '\b':
            chars.append(char)
            print(char, end='', flush=True)
        elif chars:
            chars.pop()
            print('\b \b', end='', flush=True)
    return ''.join(chars)

user = input_no_newline("Type Here: ")
print("Text")

Upvotes: 0

Samathingamajig
Samathingamajig

Reputation: 13245

Go up a line, then forward the length of the input. Note that this doesn't work if there was already text on the current line before calling noline_input

def noline_input(prompt):
    data = input(prompt)
    print(end=f"\033[F\033[{len(prompt)+len(data)+1}G") # or +2 if you want an extra space
    return data

Upvotes: 1

J_H
J_H

Reputation: 20450

The input() function is not very fancy. And it will advance the cursor down to start of next line when the user hits RETURN.

But you can overwrite what happened on that line by sending an ANSI escape sequence:

up = chr(27) + "[A"

For example:

name = input("Name? ")
print(up + "Name is " + name + "    Pleased to meet you.    ")

For fancier approaches, you will need a library like curses or GNU readline.

Upvotes: 1

Related Questions