![](/img/trans.png)
[英]How do I get python to interpret the ANSI escape codes for colors in a string read from a text file
[英]How do I utilize the input() command to include ANSI escape color codes in Python?
我对 Python 比较陌生。 我正在尝试利用 input() 函数来包含 ANSI 颜色代码,并将值存储到字典中。 我也尝试过使用 colorama 库,但想尝试使用这种方法。
red = '\x1b[91m'
reset = '\x1b[0m'
color = input()
然后用户输入输入: red+'test'+reset
应该返回'\x1b[91mtest\x1b[0m'
并通过print(color)
打印这个输入应该返回红色的字符串 'test'。
input()
将其转换为字符串"red+'test'+rest"
。 我也尝试过直接输入 ANSI 代码,但我得到的是字符串"\\x1b[91mtest\\x1b[0m"
。 有没有办法格式化它,以便我可以选择字符串中的任何位置来添加颜色? 例如,如果我希望这个脚本获得输入和功能,例如:
The "+yellow+"sun"+reset+" is bright in the "+blue+"sky"+reset+" today."
谢谢!
注意:使用python 3
好像你需要eval
red = '\x1b[91m'
reset = '\x1b[0m'
color = eval(input('Enter something: '), {'red': red, 'reset': reset})
print(color)
输出:
Enter something: red + 'hi' + reset + 'bye'
打印hibye
,但hi
是红色的, bye
是白色的。
注意: eval
可能很危险,不要让用户输入类似__import__('shutil').rmtree('/')
内容 - 您可能需要在eval
之前检查输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.