python - 如何将退格符应用于字符串

Sha*_*erz 4 python string

我有一个字符串

s = '--two \x08--three'
Run Code Online (Sandbox Code Playgroud)

当我打印时,我得到

--two--three
Run Code Online (Sandbox Code Playgroud)

但我可以做点什么吗

s='--two--three'
Run Code Online (Sandbox Code Playgroud)

没有明确声明它。

我不需要存储甚至不知道后面的空间。我只想在没有退格字符的情况下操作文本。我怎样才能做到这一点?

编辑:希望我能澄清一点。说我有两个字符串

test1 = 'a\bb' #b
test2 = 'b' #b
Run Code Online (Sandbox Code Playgroud)

当它们被打印出来时,它们等同于用户,但是test1!=test2. 我正在做的是从终端拉出一些输出。此输出始终具有退格键。我希望能够操作最终结果、搜索单词、编辑字符串而不必担心退格。

编辑 2:我想我真正想要的是将变量设置为打印语句的结果

a = print("5\bA") #a='A' #does not work like this
Run Code Online (Sandbox Code Playgroud)

Wil*_*son 6

您可以使用正则表达式对字符串应用退格:

import re

def apply_backspace(s):
    while True:
        # if you find a character followed by a backspace, remove both
        t = re.sub('.\b', '', s, count=1)
        if len(s) == len(t):
            # now remove any backspaces from beginning of string
            return re.sub('\b+', '', t)
        s = t
Run Code Online (Sandbox Code Playgroud)

现在:

>>> apply_backspace('abc\b\b\b123')
'123'
Run Code Online (Sandbox Code Playgroud)


小智 5

这可以通过使用正则表达式重复应用替换操作来解决,直到字符串不再包含退格字符。或者,一个更复杂的正则表达式可能可以一次性解决它,但我将采用更简单的解决方案。

import re

s = '--two \x08--three'

while '\x08' in s:
    s = re.replace('[^\x08]\x08', '', s)
Run Code Online (Sandbox Code Playgroud)

替换操作删除非退格字符后跟退格字符的所有实例。如果您不熟悉正则表达式,则'[^\x08]\x08'可以将表达式解码如下:

[^       # Match any single character that is NOT one of the following:
   \x08     # A backspace character
]        
\x08     # followed by a single backspace character
Run Code Online (Sandbox Code Playgroud)

您需要循环的原因是为了处理一个接一个有多个退格字符的情况。例如,对于 string 'foocar\x08\x08\x08bar',每次迭代只会删除第一个退格,如下所示:

'foocar\x08\x08\x08bar'
'fooca\x08\x08bar'
'fooc\x08bar'
'foobar'
Run Code Online (Sandbox Code Playgroud)