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)
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://stackoverflow.com/a/19926010/5276734
'\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).
来源:https://stackoverflow.com/questions/34233285/using-b-in-python-3