如何读取文件并删除字符串索引前的字符

how to read file and remove character before string index

我有一个包含以下内容的文本文件:

hello haha [BS][BS][BS][BS]idk about that [BS][BS][BS][BS]yeah no[BS][BS]

我想阅读它并基本上将它重新保存到一个新文件或只是使用 [BS] 作为退格键替换旧文件。 所以它会是...

hello idk about yeah

弄乱了一堆替代品,如 .pop() 和 .replace() 不幸的是没有运气。

编辑 2:

import re

s = "hello haha [BS][BS][BS][BS]idk about that [BS][BS][BS][BS]yeah no[BS][BS]"

out, i = "", 0
for m in re.finditer(r"(\s*\[BS\])+", s):
    c = m.group(0).count("[BS]")
    out += s[i : max(m.start() - c, 0)]
    i = m.end()
out += s[i:]

print(out)

打印:

hello idk about yeah 

已删除 \u0008 版本

这不是最有效的解决方案(如 ),我不确定您打算如何处理空格(您的描述很含糊 - 请注意您问题的评论):

from re import sub

s = "hello haha [BS][BS][BS][BS]idk about that [BS][BS][BS][BS]yeah no[BS][BS]"

while '[BS]' in s:
    s = sub(r'.?\[BS\]', '', s, count=1)

>>> s
'''
'hello hidk about tyeah '