我正在制作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
更容易使用..