[英]How to replace in string without breaking ansi escape codes?
Instead of printing而不是印刷 , the following script prints ,下面的脚本打印 . .
s = '1\x1b[1;31m2\x1b[0m3'
print(s)
s = s.replace('1', ' ')
print(s)
I understand that it is because the .replace
operation has broken the ANSI escape codes.我知道这是因为.replace
操作破坏了 ANSI 转义码。 But this is unfortunate.但这是不幸的。
What's an easy way to make .replace
, or str.translate
, or re.sub
safely ignore escape codes?有什么简单的方法可以让.replace
或str.translate
或re.sub
安全地忽略转义码?
Using the regex to match ANSI escape sequences from an earlier answer, we can make a helper function that only replaces those parts of the text that do not belong to such a sequence.使用正则表达式匹配早期答案中的 ANSI 转义序列,我们可以创建一个辅助函数,该函数仅替换文本中不属于此类序列的部分。
Assuming this is utils.py :假设这是utils.py :
import re
# https://stackoverflow.com/a/14693789/18771
ANSICODE = re.compile(r'\x1B[@-_][0-?]*[ -/]*[@-~]')
def replace_ansi(imput_str, search_str, replace_str):
pos = 0
result = []
for m in ANSICODE.finditer(imput_str):
text = imput_str[pos:m.start()]
text = text.replace(search_str, replace_str)
result.append(text)
result.append(m.group())
pos = m.end()
text = imput_str[pos:]
result.append(text)
return ''.join(result)
usage用法
from utils import replace_ansi
s1 = 'bla 1\x1b[1;31mbla 2\x1b[0mbla 3'
s2 = replace_ansi(s1, '1', 'X')
print(s1)
print(s2)
prints印刷
bla 1[1;31mbla 2[0mbla 3 bla X[1;31mbla 2[0mbla 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.