0

Can i change an already printed out character to another while having the previous deleted? For example how can a program show '_' for 2 seconds, (delete or change it) and show the character 's'?

smart
  • 161
  • 1
  • 7
  • i want to replace '_' with 's' (not numbers) – smart Jan 10 '18 at 01:52
  • @Smart Then the question [Python code to cause a backspace](https://stackoverflow.com/questions/18320431/python-code-to-cause-a-backspace-keystroke) might be a little more helpful to you. The answers are very similar to those of the duplicate, but it focuses on how to make a backspace. In particular, the newest answer shows an example of a time based erasure which is replaced by new set of characters, which you could tweak to your `"_"` to `"s"` example pretty simply. – Davy M Jan 10 '18 at 02:00
  • then change the code to that which you want: `sys.stdout.write('%s\r' % '_'); sys.stdout.flush(); time.sleep(2); sys.stdout.write('%s\n' % 's')` – chickity china chinese chicken Jan 10 '18 at 02:00

1 Answers1

0

The character for backspace is '\b'.

The usage for the task you're asking for would be something like this

import sys, time

print('I am about to show you something _\b', end='')
sys.stdout.flush() # Make sure above string gets printed in time
time.sleep(2)
print('THIS!')

In addition, the character for carriage return is '\r' and it allows you to rewrite the whole line. You could use it, for example to print a progress bar

import sys, time
for i in range(0, 50):
    print('[{}{}] {}%'.format('|' * i, '-' * (50-1-i), 2*i+2), end='\r')
    sys.stdout.flush()
    time.sleep(0.01)
print('')
Marco
  • 2,007
  • 17
  • 28
  • your first code line 3 (first 'print') generates a syntax error – smart Jan 10 '18 at 02:17
  • @smart are you sure you copy/pasted it right? It runs on my computer and on online compilers too. What does the error say? – Marco Jan 10 '18 at 02:26
  • just a syntax error – smart Jan 10 '18 at 02:27
  • @smart what python version are you using? – Marco Jan 10 '18 at 02:29
  • i am using 2.4.3 – smart Jan 10 '18 at 02:34
  • @smart so that's because `print` is still a statement, not a function. Replace it with `sys.stdout.write('I am about to show you something _\b')` – Marco Jan 10 '18 at 02:35
  • now it generates a type error: 'write() takes no keyboard arguments' – smart Jan 10 '18 at 02:39
  • @smart what if you convert the string to bytes literal? `sys.stdout.write(b'I am about to show you something _\b')` – Marco Jan 10 '18 at 02:49
  • now it generates a syntax error – smart Jan 10 '18 at 02:54
  • @smart I'm not sure why you have that type error on `write()`. See [here](https://tio.run/##TY0xDsIwEAT7vGIRhRMJpeAVpKCCEgklyhFb4FzkOxP59caBhm52pdldklqejzk7v3BQSJID1HmqqoKt6MhR2zU4pdp06D36oTRQhlhekThC2JNaN0@43wbT/IuPVxRbN9jj3D8JEgNtA@@CGjZjIhUsBZVGuPl3/c21uZ66y840OX8A) the code runs fine (except `\b` is not recognized) – Marco Jan 12 '18 at 22:53