![](/img/trans.png)
[英]How do I get python to interpret the ANSI escape codes for colors in a string read from a text file
[英]How to replace in string without breaking ansi escape codes?
使用正則表達式匹配早期答案中的 ANSI 轉義序列,我們可以創建一個輔助函數,該函數僅替換文本中不屬於此類序列的部分。
假設這是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)
用法
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)
印刷
bla 1[1;31mbla 2[0mbla 3 bla X[1;31mbla 2[0mbla 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.