Default text for Python input

Viewed 709

If I ask for user input, Python will let me use the arrow keys to move around what I typed and change it if necessary. For instance, when running the following program

user_input = input("file name -> ")
print(user_input)

I can use the left arrow to go back, change the 'G' to 'g'

file name -> thisIsAVeryLonGFileName.txt

and when I then hit Enter it prints

thisIsAVeryLongFileName.txt

Is there a way to prompt for user input with a default response already provided which then enables the user to use the arrow keys to modify the default response rather than having to type the whole response in? Basically, things should work just like above but without the user having to type anything in initially (instead it is provided by the program).

1 Answers

Rather than a pre-filled input (which would probably require some level of GUI/a lot of boilerplate), why not just have a default value built in to your program and give the user the option to choose that default?

For example, users used to command-line interfaces would likely understand that a blank input here would use the default filename:

user_input = input("file name (default: aVeryLongFilename.txt) -> ")
if user_input == "":
    user_input = "aVeryLongFilename.txt"

Or, if your users need more training wheels:

default_choice= input("use default filename, aVeryLongFilename.txt? (y/n) -> ")
if default_choice == "y":
    user_input = "aVeryLongFilename.txt"
else:
    user_input = input("file name -> ")

Obviously you'd want to validate/loop around the y/n input in the second example, but I think this is a nice middle ground between having a default and commiting yourself to using a GUI.

Edit:

In the case where you might not know what a reasonable default is until the user has run the program once, you could try something like this (inspired by hlzl's comment below), using the first suggestion above as a model:

if first_run:
    user_input = input("file name -> ")
else:
    reasonable_default = str(load_previous_run_file())
    user_input = input("file name (previous filename: " + reasonable_default + ") -> ")
    if user_input == "":
        user_input = reasonable_default
Related