Python strings: backspace at the end of string behaves differently

半腔热情 提交于 2020-06-15 06:19:33

问题


I'm experimenting with the backspace character \b in Python strings. I tried this:

>>> s = "The dog\b barks"
>>> print(s)
The do barks

This behaves as expected. The g character disappears because of the \b backspace.

Now I try this:

>>> s = "The dog barks\b"
>>> print(s)
The dog barks

Strange... the s character didn't disappear. Why?

Note:
I work on a Windows 10 PC and did these experiments in the Windows cmd prompt (the terminal). I run Python 3.6


回答1:


That isn't a behavior of python but your output StreamHandler. The \b doesn't cancel the character before it, it instructs your output handler device (terminal/console) to move the cursor backward.

What basically happens is, that you are placing the cursor one character to the left and continue streaming what is following. It visually look like you are putting a space as the next following character is aspace.

In Both Unix based and Windows the output behavior is the same:

Unix test / Mac Terminal:

echo -e "Hello test\b" 
>Hello test

Windows test / CMD / Powershell :

echo "Hello test`b"
>Hello test



回答2:


Python doesn't treat the backspace (\b) character specially, but Windows command prompt (cmd.exe) treats the backspace by moving the cursor left one character, then printing the rest of the string. Because there is nothing left to print, moving the cursor left doesn't actually do anything.



来源:https://stackoverflow.com/questions/47732236/python-strings-backspace-at-the-end-of-string-behaves-differently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!