Python 用颜色替换() 字符串?



我正在制作一个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。我该如何解决这个问题?

您必须返回更新的文本。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)

你总是可以使用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

最新更新