python - 如何将退格符应用于字符串 [英] python - how to apply backspaces to a string
问题描述
我有一个字符串
s = '--two \x08--three'
当我打印时,我得到
--二--三
但是我可以做点什么吗
s='--二--三'
无需明确声明.
我不需要存储甚至不知道后退空间.我只想在没有退格字符的情况下操作文本.我怎样才能做到这一点?
希望我能澄清一点.假设我有两个字符串
test1 = 'a\bb' #btest2 = 'b' #b
当它们被打印出来时,它们等同于用户,但是test1!=test2
.我正在做的是从终端拉出一些输出.此输出始终具有退格键.我希望能够操作最终结果、搜索单词、编辑字符串而不必担心退格.
编辑 2:我想我真正想要的是将变量设置为打印语句的结果
a = print("5\bA") #a='A' #不会像这样工作
您可以使用正则表达式对字符串应用退格:
导入重新def apply_backspace(s):为真:# 如果你发现一个字符后跟一个退格,删除两个t = re.sub('.\b', '', s, count=1)如果 len(s) == len(t):# 现在删除字符串开头的所有退格return re.sub('\b+', '', t)s = t
现在:
<预><代码>>>>apply_backspace('abc\b\b\b123')'123'I have a string
s = '--two \x08--three'
When I print, I get
--two--three
but can I do something to have
s='--two--three'
with out declaring it explicitly.
I do not need to store or even know about the back spaces. I just want to manipulate the text without the backspace characters there. How can I achieve this?
Edit: Hopefully I can clarify a little. Say I have two strings
test1 = 'a\bb' #b
test2 = 'b' #b
When they are printed, they are equivalent to the user, but test1!=test2
. What I am doing is pulling some output from a terminal. This output has backspaces throughout. I want to be able to manipulate the end result, search for words, edit the string without worrying about the backspaces.
Edit 2: I guess what I really want is to set a variable as the result of a print statement
a = print("5\bA") #a='A' #does not work like this
You can apply backspaces to a string using regular expressions:
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
Now:
>>> apply_backspace('abc\b\b\b123')
'123'
这篇关于python - 如何将退格符应用于字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!