Python replace()字符串是否带有颜色?

问题描述 投票:2回答:2

我正在制作Python语法荧光笔,基本上它的作用是用相同字符串的彩色版本替换输入字符串中的关键字。这是我的代码示例(整个程序基本上只是复制并粘贴此代码)

from colorama import Fore
def highlight(text):
  text = text.replace("print", "{}print{}".format(Fore.BLUE, Fore.RESET))
print(text)

但是当我尝试使用以下代码时:

highlight("print hello world")

((注:我没有放在方括号中,因为这只是一个测试)它只是以默认颜色打印了print hello world。我该如何解决?

编辑:感谢您的声誉! 😁

python syntax-highlighting colorama
2个回答
2
投票

您必须返回更新的文本。 Strnigs在python中是不可更改的,因此,如果您更改某些字符串,则在内部不会更改,它将是一个新字符串。

from colorama import Fore

def highlight(text):
    return text.replace("print", "{}print{}".format(Fore.BLUE, Fore.RESET))

text = highlight("print hello world")
print(text)

1
投票

您可以始终使用CLINT。

from clint.textui import puts, colored
puts(colored.red('Text in Red')) 
#Text in Red

更容易使用..

https://clint-notes.readthedocs.io/en/latest/howto.html

© www.soinside.com 2019 - 2024. All rights reserved.