I have a text file that has the following:
hello haha [BS][BS][BS][BS]idk about that [BS][BS][BS][BS]yeah no[BS][BS]
I would like to read it and essentially re save it to a new file or just replace the old file using the [BS] as a backspace. so it would then be...
hello idk about yeah
Messed around with a bunch of alternatives like .pop() and .replace() no luck unfortunately.
CodePudding user response:
EDIT 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)
Prints:
hello idk about yeah
Removed \u0008
version
CodePudding user response:
this is not the most efficient solution (like that), and i'm not sure how you suppose to handle spaces (your description is quite ambiguous - note the comment to your question):
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 '