简体   繁体   English

如何在不破坏ansi转义码的情况下替换字符串?

[英]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?有什么简单的方法可以让.replacestr.translatere.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.

相关问题 如何让 python 解释从文本文件读取的字符串中 colors 的 ANSI 转义码 - How do I get python to interpret the ANSI escape codes for colors in a string read from a text file 如何检测控制台是否支持Python中的ANSI转义码? - How to detect if the console does support ANSI escape codes in Python? 如何使用变量格式化带有 ANSI 转义码的打印语句? - How to format print statement with ANSI Escape Codes using variables? ANSI 转义码在 IDLE 上不起作用……(python) - ANSI escape codes not working on IDLE… (python) 在python中处理终端颜色代码(ANSI颜色转义代码) - Handling terminal colour codes ( ANSI colour escape codes ) in python 如何从 python 中的字符串中删除 ANSI 转义序列 - How can I remove the ANSI escape sequences from a string in python 如何使用ansi转义码为python中的特定字符单元着色,其中字符单元格位置由变量确定 - How to colour a specific character cell in python using ansi escape codes where the character cell location is determined by variables Python:如何使 ANSI 转义码也能在 Windows 中工作? - Python: How can I make the ANSI escape codes to work also in Windows? 如何让 powershell 或 windows 终端使用 ANSI 转义码打印彩色文本? - How do I get powershell or windows terminal to print color text using ansi escape codes? 如何利用 input() 命令在 Python 中包含 ANSI 转义颜色代码? - How do I utilize the input() command to include ANSI escape color codes in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM