Python 语句中的退格行为,在代码中打印“\b"的正确行为是什么? [英] Backspace behavior in Python statement, what is correct behavior of printing a '\b' in code?

查看:103
本文介绍了Python 语句中的退格行为,在代码中打印“\b"的正确行为是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

可能的重复:
退格字符怪异

我注意到了1. 如果我只打印退格,即 Python 中的 \b 序列,那么它是完全空白的.2.如果我打印字符后跟退格符,即'sssss\b\b\b\b\b',那么它会打印多个's'字符但是,如果我打印诸如 'ssss\b\b\b\baaaa' 之类的内容,那么退格符 \b 实际上就像我在键入退格符并删除了 's' 字符一样.

我在 Windows XP 上使用 Python 2.6.这是预期的行为.如果我尝试获取退格字符的长度,则将其打印为 1.

这是我的测试代码 -

<预><代码>>>>打印 'ssss\b\b\b\b\baaaaa'啊啊啊>>>打印 'ssssssss\b\b\b\b\baaaaa'sssaaaa>>>打印 'ssssssss\b\b\b\b\b'sssssss>>>打印 'ssssssss\b\b\b\b\baaaaa'sssaaaa>>>打印 '\b\b\b\b\b'>>>

我的问题是 - 当我在 Python 中打印 '\b' 时的预期行为是什么,为什么删除只在特定情况下有效?

解决方案

扩展答案:退格键不会删除任何内容,它会将光标向左移动,然后被您之后编写的内容覆盖.如果您正在向可以显示重击的设备(例如老式的硬拷贝"终端,其工作方式类似于打字机)进行写入,您实际上会在旧字符的顶部看到新字符.这就是退格键具有这些语义的真正原因.

在 unix 命令行上,可以将 shell 设置为将退格解释为擦除"——除非它设置为仅以这种方式处理删除.但这取决于读取您输入的程序.

Possible Duplicate:
backspace character weirdness

I have noticed that 1. If I print only backspaces, i.e. a sequence of \b in Python, then it is completely blank. 2. If I print characters followed by backspaces i.e. 'sssss\b\b\b\b\b', then it will print the multiple 's' characters But if I print something like 'ssss\b\b\b\baaaa', then the backspace, \b, will actually act like I am typing a backspace and delete the 's' characters.

I am using Python 2.6 on Windows XP. Is this expected behavior. If I try to get length of backspace character, it is printed as 1.

Here is my test code -

>>> print 'ssss\b\b\b\b\baaaaa'
aaaaa
>>> print 'ssssssss\b\b\b\b\baaaaa'
sssaaaaa
>>> print 'ssssssss\b\b\b\b\b'
ssssssss
>>> print 'ssssssss\b\b\b\b\baaaaa'
sssaaaaa
>>> print '\b\b\b\b\b'

>>>

My question is- What is the expected behavior when I print '\b' in Python and why the deletion does work in only a particular case?

解决方案

Expanded answer: The backspace doesn't delete anything, it moves the cursor to the left and it gets covered up by what you write afterwards. If you were writing to a device that can display overstriking (such as an old-fashioned "hard copy" terminal, which works like a typewriter), you'd actually see the new character on top of the old one. That's the real reason backspace has these semantics.

On the unix command line, the shell can be set to interpret backspace as meaning "erase"-- unless it's set to only treat delete this way. But that's up to the program reading your input.

这篇关于Python 语句中的退格行为,在代码中打印“\b"的正确行为是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆