Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console colored text changes string length

In Windows, The Colored Console Text module called colorama changes colors but it also changes string length too.

How do I avoid this?

My Code:

from colorama import * #Not only colorama
init(convert=True)

my_text = Fore.LIGHTCYAN_EX+"Hello World!"
print(mytext, len(my_text))

#Output: Hello World! 17

So I want 12 length but module adds 5 more characters.

like image 996
ForceVII Avatar asked Sep 20 '25 18:09

ForceVII


1 Answers

This is because to add colour they are adding hidden characters to the start of the string that tells the thing displaying it to use a colour. You can look at the actual value of you text by printing it like this:

from colorama import * #Not only colorama
init(convert=True)

my_text = Fore.LIGHTCYAN_EX+"Hello World!"
print(repr(my_text), len(my_text))

which will output '\x1b[96mHello World!' 17

If you want to keep getting the length of the text perhaps you would be better off storing it in the variable as "Hello World!" and only adding Fore.LIGHTCYAN_EX when displaying it

like image 53
Quinn Avatar answered Sep 22 '25 08:09

Quinn