I'm writing a text game in Python. I've written a function which takes a list of words and changes their colour, while leaving the rest white.
def highGreen(text, words):
textWords = text.split(" ")
highlight = set(textWords).intersection(words)
for word in textWords:
if word in highlight:
print("\033[32m", end="")
print(word, end=" ")
else:
print("\033[0m", end="")
print(word, end=" ")
My problem is that I can't seem to combine this function with textwrap.wrap or .fill, so when printed onto the console words are broken in random places.
I've tried:
text = "This bed is super uncomfortable."
for line in textwrap.wrap(text, 80):
highGreen(line, ["bed"])
but it still prints everything in one line.
The colouring is done in such a weird way because nothing else I tried worked in the Windows 10 console/PyCharm.
Firstly, your text isn't 80 characters long (in fact it's only 32) so it would all fit on one line anyway. Let's change that to 20 for this example.
Secondly, Your text would be broken up into 20 character chunks, you're just not printing any newlines. print() usually adds them automatically but since you override that with the end= argument the new line is never printed.
We can fix this by adding a empty print() statement after you call highGreen. (Remember, print() automatically prints a newline if you don't specify the end= arg)
Example:
text = "This bed is super uncomfortable."
for line in textwrap.wrap(text, 20):
highGreen(line, ["bed"])
print() # add this to print newline
Output:
This bed is super
uncomfortable.
(The bed prints out green, I'm just not sure how to copy that into StackOverflow)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With