How to set a default editable string for raw_input?
Python2.7 get raw_input and set a default value:
Put this in a file called a.py:
import readlinedef rlinput(prompt, prefill=''): readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return raw_input(prompt) finally: readline.set_startup_hook()default_value = "an insecticide"stuff = rlinput("Caffeine is: ", default_value)print("final answer: " + stuff)
Run the program, it stops and presents the user with this:
el@defiant ~ $ python2.7 a.pyCaffeine is: an insecticide
The cursor is at the end, user presses backspace until 'an insecticide' is gone, types something else, then presses enter:
el@defiant ~ $ python2.7 a.pyCaffeine is: water soluable
Program finishes like this, final answer gets what the user typed:
el@defiant ~ $ python2.7 a.py Caffeine is: water soluablefinal answer: water soluable
Equivalent to above, but works in Python3:
import readline def rlinput(prompt, prefill=''): readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return input(prompt) finally: readline.set_startup_hook()default_value = "an insecticide"stuff = rlinput("Caffeine is: ", default_value)print("final answer: " + stuff)
More info on what's going on here:
In dheerosaur's answer If user press Enter to select default value in reality it wont be saved as python considers it as '' string so Extending a bit on what dheerosaur.
default = "Jack"user_input = raw_input("Please enter name: %s"%default + chr(8)*4)if not user_input: user_input = default
Fyi .. The ASCII value
of backspace is 08