我有一個包含以下內容的文本檔案:
hello haha [BS][BS][BS][BS]idk about that [BS][BS][BS][BS]yeah no[BS][BS]
我想閱讀它并基本上將其重新保存到一個新檔案中,或者只是使用 [BS] 作為退格鍵替換舊檔案。所以它會是......
hello idk about yeah
搞砸了一堆替代品,如 .pop() 和 .replace() 不幸的是沒有運氣。
uj5u.com熱心網友回復:
編輯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版本
uj5u.com熱心網友回復:
這不是最有效的解決方案(就像那樣),而且我不確定您應該如何處理空格(您的描述很模棱兩可 - 請注意對您問題的評論):
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 '
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464533.html
標籤:Python python-3.x 细绳 列表 文件
