>>> print("x\by")
y
print("a", end="")
print("a", end="")
print("a", end="")
print("h", end="")
aaah
But with multiple print statements, I am getting this output -
print("a\b", end="")
print("a\b", end="")
print("a\b", end="")
print("h\b", end="")
a a a h
Why did it print extra space after each character.
The code works fine when executed from the Windows command line, I tested it in Pycharm's console.
But in python repl, the \b
erases the previous character while it is supposed to move cursor a character backward.
>>> print("a\b", end="")
>>>
Each terminal or console is free to handle the \b
character differently. All Python can do is write out the data to sys.stdout
.
Here, the console you are using will move the cursor onwards for separate write calls, it appears. And the \b
character doesn't erase anything in the console, it merely moves the cursor back a spot within the same write call.
So for print('x\by', end='')
the console outputs x
, moves back a step, outputs y
in the same place, and now has recorded that it wrote 3 characters, so the output position is set to column 3. The next print()
will start outputting data from that new position.
Your print()
code happens to work on most terminals or consoles, because most of those don't care about how many characters you output, only where the cursor currently has been positioned. But that you have a console that behaves differently is not Python's fault.
When using the Python interactive interpreter, take into account that it too prints; so using print("a\b", end="")
leaves Python to then overwrite the line with the next >>>
prompt:
>>> print("a\b", end="")
>>>
Use print("a\b\n", end="")
instead and you'll see the a
is still there:
>>> print("a\b\n", end="")
a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With