【发布时间】:2016-08-03 05:45:09
【问题描述】:
我正在尝试将控制字符(例如应该删除前面字符的 '\x08 \x08')应用于字符串(向后移动、写入空格、向后移动)
例如,当我输入 python 控制台时:
s = "test\x08 \x08"
print s
print repr(s)
我进入我的终端:
tes
'test\x08 \x08'
我正在寻找一个函数,我们说“函数”,它将“应用”控制字符到我的字符串:
v = function("test\x08 \x08")
sys.stdout.write(v)
sys.stdout.write(repr(v))
所以我得到了一个“干净”、无控制字符的字符串:
tes
tes
我知道在终端中,这部分是由客户端处理的,所以也许有一种方法可以使用核心 unix 函数来获取 显示的字符串
echo -e 'test\x08 \x08'
cat file.out # control char are here handled by the client
>> tes
cat -v file.out # which prints the "actual" content of the file
>> test^H ^H
【问题讨论】:
-
您可以将退格处理为
'\r'(即回车),然后写入前面的字符串,但我认为这会很尴尬。 -
控制字符取决于终端类型,它们保存在 terminfo 或 termcap 数据库中。因此,python 将不得不使用这些数据库将 \x08 转换为您认为它对您的特定终端类型意味着什么。如果你只使用这些字符中的一小部分,那么你可以自己弄清楚。这些数据来自哪里?另见docs.python.org/3/library/termios.html#module-termios
标签: python string backspace control-characters repr