How to set a default editable string for raw_input?

You could do:

i = raw_input("Please enter name[Jack]:") or "Jack"

This way, if user just presses return without entering anything, "i" will be assigned "Jack".


Python2.7 get raw_input and set a default value:

Put this in a file called a.py:

import readline
def 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.py
Caffeine 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.py
Caffeine is: water soluable

Program finishes like this, final answer gets what the user typed:

el@defiant ~ $ python2.7 a.py 
Caffeine is: water soluable
final 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:

https://stackoverflow.com/a/2533142/445131