I'm using python2.7's raw_input
to read from stdin.
I want to let the user change a given default string.
Code:
i = raw_input("Please enter name:")
Console:
Please enter name: Jack
The user should be presented with Jack
but can change (backspace) it to something else.
The Please enter name:
argument would be the prompt for raw_input
and that part shouldn't be changeable by the user.
Python2.7 get raw_input and set a default value:
Put this in a file called a.py:
Run the program, it stops and presents the user with this:
The cursor is at the end, user presses backspace until 'an insecticide' is gone, types something else, then presses enter:
Program finishes like this, final answer gets what the user typed:
Equivalent to above, but works in Python3:
More info on what's going on here:
https://stackoverflow.com/a/2533142/445131
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.
Fyi .. The
ASCII value
of backspace is08
I only add this because you should write a simple function for reuse. Here is the one I wrote:
On platforms with
readline
, you can use the method described here: https://stackoverflow.com/a/2533142/1090657On Windows, you can use the msvcrt module:
Note that arrows keys don't work for the windows version, when it's used, nothing will happen.
Try this:
raw_input("Please enter name: Jack" + chr(8)*4)
The ASCII value of
backspace
is08
.You could do:
This way, if user just presses return without entering anything, "i" will be assigned "Jack".