Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python replace() string with color?

I'm making a Python Syntax Highlighter and basically what it does is replaces keywords in the entered string with colored versions of the same string. Here's a sample of my code (the whole program is basically just copy+pasting this code)

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

But when I try to use the following code:

highlight("print hello world")

(NOTE: I didn't put brackets because this was simply a test) It just printed print hello world in the default color. How can I fix this?

like image 278
Donoru Avatar asked Feb 07 '26 09:02

Donoru


2 Answers

You have to return updated text. Strnigs are not changeable in python, so if you change some string it will not be change internally, it will be a new string.

from colorama import Fore

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

text = highlight("print hello world")
print(text)
like image 52
ncopiy Avatar answered Feb 09 '26 03:02

ncopiy


You could always use CLINT.

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

Much easier to use..

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

like image 40
shaggs Avatar answered Feb 09 '26 01:02

shaggs