6

In the console you can print "\b" to erase the character left of the cursor (backspace) like this

print "the last char is going to be erased\b" # the last char is going to be erased

How to just move one position to the left instead of erasing (left arrow)?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
peter
  • 41,770
  • 5
  • 64
  • 108

1 Answers1

10

It depends on the terminal type and connection, but you can usually assume ANSI cursor movement, so cursor-left is ESC + '[' + 'D':

print "The cursor should be between the arrows: -> <-\e[D\e[D\e[D"
readline

See http://ascii-table.com/ansi-escape-sequences.php for more information.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
  • 1
    Mark, i get "The cursor should be here:> <←[D←[D" in a standard windows 7 console, the escape sequences are clearly not interpreted, but \b is although it must be followed with another character. eg 'print "The cursor should be here:>\b "' gives "The cursor should be here:" – peter Apr 22 '12 at 01:53
  • 2
    Windows doesn't interpret ANSI escapes. I don't think I could dev on a Windows machine; I'd feel like I were constantly jumping through hoops. – d11wtq Apr 22 '12 at 09:13
  • @Mark: It has challenges but your customers need to be able to run your code and since most customers have windows it's the easiest way. About the ansi stuff, there are gems that should make this possible but i'm reluctant to use these for such a simple job. After all if \b works (obviously no ansi), why should't there been something like that to move the cursor ? – peter Apr 22 '12 at 12:07
  • 1
    (peter: that last comment was from @d11wtq, not me). I'm afraid the Windows console doesn't support ANSI sequences; backspace works because the native emulator understands it directly, not because it's being translated into something else. You could install a third-party console app (Ansicon, Console...), or else make direct Win32 API calls instead of echoing characters (e.g. `SetConsoleCursorPosition()`). – Mark Reed Apr 22 '12 at 13:29