How to set a default string for raw_input

I'm using raw_input to read from stdin. I want to let the user change a given default string.


i = raw_input("Please enter name:")


Please enter name: Jack

The user should be presented with "Jack" but can change it to something else. The Please enter name: part would be the prompt for raw_input but this can't be changed by the user...any ideas?

5 Answers
  1. 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".

    2014-11-14 11:04:22
  2. 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

    2013-12-03 12:34:05
  3. Try this: raw_input("Please enter name: Jack" + chr(8)*4)

    The ASCII value of backspace is 08.

    2013-04-06 09:29:17
  4. On platforms with readline, you can use the method described here:

    On Windows, you can use the msvcrt module:

    from msvcrt import getch, putch
    def putstr(str):
        for c in str:
    def input(prompt, default=None):
        if default is None:
            data = []
            data = list(default)
        while True:
            c = getch()
            if c in '\r\n':
            elif c == '\003': # Ctrl-C
                raise KeyboardInterrupt
            elif c == '\b': # Backspace
                if data:
                    putstr('\b \b') # Backspace and wipe the character cell
            elif c in '\0\xe0': # Special keys
        return ''.join(data)

    Note that arrows keys don't work for the windows version, when it's used, nothing will happen.

    2011-03-23 12:12:26
  5. I only add this because you should write a simple function for reuse. Here is the one I wrote:

    def default_input( message, defaultVal ):
        if defaultVal:
            return raw_input( "%s [%s]:" % (message,defaultVal) ) or defaultVal
            return raw_input( "%s " % (message) )
    chubbsondubs2011-03-23 11:19:13
Related Articles
You Might Also Like