Python:\b的行为与书中的描述不同

2024-03-29 09:31:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读《用python自动化无聊的东西》,我看到了这个片段:

print(positionStr, end='')
print('\b' * len(positionStr), end='', flush=True)

其中positionStr是前面定义的字符串。我查看了python转义序列,发现\b是backspace,但出于某种原因,作者说应该删除打印的字符串

To erase text, print the \b backspace escape character. This special character erases a character at the end of the current line on the screen. The line at u uses string replication to produce a string with as many \b characters as the length of the string stored in positionStr, which has the effect of erasing the positionStr string that was last printed.

  1. 这与我在here(中间页的表格)中看到的内容相矛盾
  2. 这与我的结果不同

如您所见,我得到了一堆backspace字符,我想我应该已经得到了(我运行了一个循环,在这个循环中我打印了所说的字符串,然后打印了\b字符串)

现在,这本书是错的,还是我应该做些不同的事情来让它发挥作用?此外,如果这是错误的,有没有办法实现这个目标?(打印字符串,然后将其删除)

从图中可以看出,我使用的是python3.5.3。在Windows 8.1上


Tags: ofthe字符串truestringlenasline
1条回答
网友
1楼 · 发布于 2024-03-29 09:31:14

并不是所有的控制台都支持\b字符作为删除字符,尤其是图形控制台。你知道吗

(同样的事情发生在您将其写入文件时,前面的字符也不会被删除)

在本机shell中尝试您的示例(可以使用Windows或Linux),字符将被正确删除。你知道吗

Windows命令:

>>> print("a\bc")
c

PyScripter(这就是我所拥有的):

>>> print("a\bc")
a<strange char>c

相关问题 更多 >