'\b' 字符如何存储在 python 中的字符串中"? [英] How is a '\b' character stored in a string in python"?

查看:40
本文介绍了'\b' 字符如何存储在 python 中的字符串中"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字符串

dummy_path = "这是一个虚拟路径\基本"

\b 字符当然是一个退格,所以它被打印(并由文件系统调用处理)为

<块引用>

这是一个虚拟的patasic

(Patasic,好名字!)

我是否有机会检测到这种情况并警告用户(我自己)dummy_path 中的 \ 应该被转义或替换为/?

解决方案

你可以自己看看:

<预><代码>>>>dummy_path = "这是一个虚拟路径\基本">>>虚拟路径'这是一个虚拟路径\x08asic'

len 函数也反映了这一点:

<预><代码>>>>len("a\bc")3>>>a\bc"'a\x08c'>>>打印(a\bc")C

与带有两个字符串作为参数的 in 运算符一样:

<预><代码>>>>a\bc"中的\b"真的

如何显示完全取决于您的输出设备.大多数终端会一个接一个地打印每个字符.\b 不是可见的,而是简单地将光标向左重新定位一个位置,此时 a 会覆盖之前编写的 h.

值得注意的是,这是手册页显示粗体文本的方式.手册页(*roff 代码的屏幕渲染)使用字母-退格-字母序列来指示应以粗体显示字母.这个比喻来自打字机:用粗体输入一个字母,你输入一次,退格,然后在第一个字母上再输入一次.类似地,下划线可以表示为字母-退格-下划线.

If I have a string

dummy_path = "this is a dummy path\basic"

The \b character is of course a backspace, so this get printed (and processed by filesystem calls) as

this is a dummy patasic

(Patasic, nice name!)

Do I have a chance to detect this situation and warn the user (myself) that the \ in dummy_path should be, for example, either escaped or substituted with a /?

解决方案

You can see for yourself:

>>> dummy_path = "this is a dummy path\basic"
>>> dummy_path
'this is a dummy path\x08asic'

The len function also reflects this:

>>> len("a\bc")
3
>>> "a\bc"
'a\x08c'
>>> print("a\bc")
c

as does the in operator with two strings as arguments:

>>> "\b" in "a\bc"
True

How it is displayed is entirely dependent on your output device. Most terminals will print each character one after the other. The \b, instead of being visible, simply repositions the cursor one position to the left, at which point the a overwrites the previously written h.

Notably, this is how a man page displays bold text. Man pages (which are on-screen renderings of *roff code) use letter-backspace-letter sequences to indicate a letter should be displayed in bold face. The metaphor comes from typewriters: to type a letter in bold, you type it once, backspace, then type it again over the first one. Similarly, underlining can be represented as letter-backspace-underscore.

这篇关于'\b' 字符如何存储在 python 中的字符串中"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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