[英]How do I utilize the input() command to include ANSI escape color codes in Python?
I'm relatively new to Python.我对 Python 比较陌生。 I'm trying to utilize the input() function to include ANSI color codes, and store the values to a dictionary.我正在尝试利用 input() 函数来包含 ANSI 颜色代码,并将值存储到字典中。 I've tried using the colorama library too but wanted to try using this approach.我也尝试过使用 colorama 库,但想尝试使用这种方法。
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.然后用户输入输入: red+'test'+reset
应该返回'\x1b[91mtest\x1b[0m'
并通过print(color)
打印这个输入应该返回红色的字符串 'test'。
The input()
turns it into a string "red+'test'+rest"
instead. input()
将其转换为字符串"red+'test'+rest"
。 I've also tried directly typing in the ANSI code but I get the string "\\x1b[91mtest\\x1b[0m"
instead.我也尝试过直接输入 ANSI 代码,但我得到的是字符串"\\x1b[91mtest\\x1b[0m"
。 Is there a way to format it so I can choose anywhere in the string to add colors?有没有办法格式化它,以便我可以选择字符串中的任何位置来添加颜色? eg if I wanted this script to get inputs and function like:例如,如果我希望这个脚本获得输入和功能,例如:
The "+yellow+"sun"+reset+" is bright in the "+blue+"sky"+reset+" today."
Thanks!谢谢!
Note: using python 3注意:使用python 3
Seems like you need eval
好像你需要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.打印hibye
,但hi
是红色的, bye
是白色的。
Note: eval
can be dangerous, don't let the user enter something like __import__('shutil').rmtree('/')
- you might want to check the input before eval
uating注意: eval
可能很危险,不要让用户输入类似__import__('shutil').rmtree('/')
内容 - 您可能需要在eval
之前检查输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.