Using \b in Python 3
Asked Answered
I

2

4

I saw in another question that ("\b") could be used to delete a character. However, when I tried \b it only put a space in between the character I was intending on deleting and the one after. Is there another way I could do backspace?

(I'm trying to make a program that will write a word, delete it then rewrite a new one)

Implant answered 11/12, 2015 at 22:3 Comment(1)
Depends. "\b" deletes a character, but depends on where it was printed. Do you have an example?Behling
L
5

It depends on the terminal which is used and how it interprets the \b, e.g.

print('Text: ABC\b\b\bXYZ')

in the interactive console of PyCharm gives:

Text: ABC   XYZ

but executed in the comand line (cmd.exe) it gives:

Text: XYZ

This is explained in more detail here: https://mcmap.net/q/752322/-39-b-39-doesn-39-t-print-backspace-in-pycharm-console

Lesbian answered 11/12, 2015 at 22:30 Comment(1)
What would I used to backspace if it is being executed in shell?Implant
F
3

'\b' only deletes when printing to a terminal (and not necessarily all terminals, though common *NIX shells and cmd.exe should work). If the output is going to a file (or anywhere else besides a terminal), it's going to insert the literal ASCII backspace character.

If you're writing to anything but a terminal, the easiest way to undo what you've recently written would be to seek back and truncate away the bit you don't want, e.g.:

import io

with open(filename, 'wb') as f:
    ... Do stuff ...
    f.write(b'abcdefg')
    ... Do other stuff that doesn't write to the file ...
    # Oh no, it shouldn't be abcdefg, I want xyz
    f.seek(-len(b'abcdefg'), io.SEEK_CUR)  # Seek back before bit you just wrote
    f.truncate()  # Remove everything beyond the current file offset
    f.write(b'xyz')  # Write what you really want

You can toggle between writing backspaces and doing seek and truncate based on whether you're outputting to a terminal; file-like objects have the .isatty() method that returns True when connected to a terminal, and False otherwise.

Of course, if you're not connected to a terminal, and not writing to a seekable medium (e.g. piping your program to another program), then you're stuck. Once you've written, it's done, you can't undo it in the general case (there are exceptions involving buffering, but they're flaky and not worth covering).

Farmhand answered 11/12, 2015 at 22:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.