简体   繁体   中英

How can i have a default value in cursor place for the user input in python?

I would like to have a default value in the user input cursor.

option = input("Chose an option 1. run, 0. exit to run the output: ") or 1

I have tried the above code, but it didn't work for me.

When I run the below example code. Example:

option = input("Chose an option 1. run, 0. exit to run the output: ")

Expected output:

Chose an option 1. run, 0. exit to run the output: 1

By default 1 should be listed in the user input cursor, either user can enter directly or modify it before pressing enter key.

rx7 module has an function for this question.

(This only work on windows)

import rx7
rx7.Input(prompt, default_value)
# e.g
rx7.Input("Chose an option 1. run, 0. exit to run the output: ",'1')

(I know It's been 11 months since your question but still hope it helps you)

def prompt(prompt, default_value):
    answer = input(prompt + ' ' + default_value + '\r' + prompt + ' ')
    if answer == "": answer = default_value
    return answer

choice = prompt('Do you want to clear the contents of this folder [Y/n]?', 'Y')

The secret here is \\r which will make the cursor go back to the start of the line without overwriting the text. You then overwrite the text with the prompt without printing the default value et voila ... If the answer is an empty string, the we return the default_value.

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