Home > Software design >  How can I get carriage returns to work with input() in Python 3
How can I get carriage returns to work with input() in Python 3

Time:08-06

Intro

I am trying to run a script that involves taking names from user input until the input becomes "DONE", but I am wanting the userinput to stay in the sameline until the input becomes so.

What I Want

Enter a name (John D) or DONE
----------
Adam B #after input, turns blank and waits for another name on same line 
Bob D #on same line as mentioned before
Done #on same line as mentioned before
----------
#finish code

What I Get

Enter a name (John D) or DONE
----------
Adam B # each iteration still newlines
Bob D # newline
Done #newline 
----------
#finish code

Troubleshooting

I have looked over the forums here and on other websites and only found answers pertaining to print() and single-input, not for one or more inputs. I am surprised I am the only one with this issue and makes me wonder if I am overlooking something obvious.

Code Snippet

. . .
done = False
i = 0
prompt = "Enter a name (John D) or DONE\n----------\n\r"
print(prompt, end='')
    
#start loop for entering names as needed, aka 'until they type done'
    
while done == False:
    #ask what to do, and convert whatever they type into all uppercase      
    usrinput = input(''   '\r').upper()
    #check if user typed done
    if usrinput != "DONE":
        #if not, use i variable to manually iterate and add each name to the placeholder "custlog"
        custlog[i] = usrinput
        #print current name for reference or debug, then add 1 for each iteretion
        #print("%s\r" % custlog[i])
        i = i   1
    #but if they did enter done..
    elif usrinput == "DONE":
       . . .

CodePudding user response:

I think the only way is to do it "manually" by going up one line and then delete it:

usrinput = input().upper()
print ('\033[1A\033[K', end='')

or with the sys library:

import sys

usrinput = input().upper()
sys.stdout.write('\x1b[1A')
sys.stdout.write('\x1b[2K')
  • Related