Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I utilize the input() command to include ANSI escape color codes in Python?

I’m relatively new to Python. I’m trying to utilize the input() function to include ANSI color codes, and store the values to a dictionary. I’ve tried using the colorama library too but wanted to try using this approach.

red = '\x1b[91m'
reset = '\x1b[0m'

color = input()

The user then types in the input: red+'test'+reset which should return '\x1b[91mtest\x1b[0m' and printing this input via print(color) should return the string ‘test’ that is colored red.

The input() turns it into a string "red+'test'+rest" instead. I’ve also tried directly typing in the ANSI code but I get the string "\\x1b[91mtest\\x1b[0m" instead. Is there a way to format it so I can choose anywhere in the string to add colors? e.g. if I wanted this script to get inputs and function like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The "+yellow+"sun"+reset+" is bright in the "+blue+"sky"+reset+" today."

Thanks!

Note: using python 3

>Solution :

Seems like you need eval

red = '\x1b[91m'
reset = '\x1b[0m'

color = eval(input('Enter something: '), {'red': red, 'reset': reset})
print(color)

Output:

Enter something: red + 'hi' + reset + 'bye'

Prints hibye but the hi is red and the bye is white.


Note: eval can be dangerous, don’t let the user enter something like __import__('shutil').rmtree('/') – you might want to check the input before evaluating

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading