gpt4 book ai didi

Python replace() 带颜色的字符串?

转载 作者:行者123 更新时间:2023-12-04 02:35:03 51 4
gpt4 key购买 nike

我正在制作一个 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)

关于Python replace() 带颜色的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62366169/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com