简体   繁体   中英

How to print a message in same line as a input? (python)

When the user confirms the input i want to print a message in the same line of the input, in this case, a symbol of correct or incorrect.

I tried using end='', but it doesn't seem to work

answer = input('Capital of Japan: ', end=' ')
if answer == 'Tokyo':
    print('✔')
else:
    print('❌')

So if the user type 'Tokyo', that is what i expected to show up:

Capital of Japan: Tokyo ✔ 

Instead, i get this error:

    answer = input('Capital of Japan: ', end=' ')
TypeError: input() takes no keyword arguments

If your terminal supports ANSI CSI codes then:

CSI = '\x1B['
q = 'Capital of Japan: '
answer = input(q)
c = len(q) + len(answer)
result = '✔' if answer == 'Tokyo' else '❌'
print(f'{CSI}F{CSI}{c}C {result}')

CSI n F moves cursor to previous line. n defaults to 1.

CSI n C moves cursor forward n positions. n defaults to 1

Example:

Capital of Japan: Tokyo ✔

you can accomplish your task with help of ANSI escape codes. use this:

    import colorama as cr

    cr.init(autoreset=True)
    LINE_UP = "\033[1A"
    LINE_CLEAR = "\x1b[2K"
    Question = "Capital of Japan: "
    answer = input(Question)
    if answer == "Tokyo":
        print(LINE_UP, LINE_CLEAR, Question + answer + 
              f"{cr.Fore.GREEN} ✔")
    else:
        print(LINE_UP, LINE_CLEAR, Question + answer + 
              f"{cr.Fore.RED} ❌")

with help of colorama you can print colorful text in terminal. LINE_UP set the cursor to previous line and LINE_CLEAR clear the hole line for new text

answer = input('Capital of Japan: ')
print('Capital of Japan: ', answer, ' ', end='', flush=True)
if answer == 'Tokyo':
    print('✔', end='')
else:
    print('❌', end='')

or

answer = input('Capital of Japan: ', end=' ')
if answer == 'Tokyo':
    print('✔', end='')
else:
    print('❌', end='')

I think it really can't be done. Try it with \b which will position the cursor on the last line of the cmd. I tried it this way:

answer = input('Capital of Japan: ')
if answer == 'Tokyo':print(f'\b\bCapital of Japan: {answer} ✔', end=' ')
else:print(f'\b\bCapital of Japan: {answer} ❌', end=' ')

But I haven't gotten it to work. One solution I've come up with is to print another line below, and find some spacing for the icons/emogi to be positioned below the response. The code is like this.

answer = input(print('Capital of Japan: ', end=' '))
if answer == 'Tokyo':print('\b' + ' ' * len('Capital of Japan: ') + '✔', end=' ')
else:print('\b' + ' ' * len('Capital of Japan: ') + '❌', end=' ')

Gives a result something like this:

Capital of Japan:  example
                  ❌
Capital of Japan:  Tokyo            
                  ✔

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM