我试图让文本在 ipython 的 qtconsole 中显示为粗体、颜色或斜体。
我找到了这个链接:How do I print bold text in Python? , 并使用了第一个和第二个答案,但在 qtconsole 中,只有下划线选项有效。
我尝试:
print '\033[1m' + 'Hello World!' + '\033[0m'
并得到:
你好,世界!
(无粗体)。颜色也不行。但是:
print '\033[4m' + 'Hello World!' + '\033[0m'
并得到:
你好,世界!
带下划线。
这仅在 qtconsole 中。仅在终端中运行 ipython,它可以通过这种方式进行粗体和颜色处理。
该链接中还建议了其他选项和另一个 Print in terminal with colors using Python? ,从它链接,但它们看起来都比我想做的事情似乎更复杂,并且使用更复杂的包,这只是让 qtconsole 像普通终端一样显示。
有人知道这是怎么回事吗?这仅仅是 qtconsole 的限制吗?
最佳答案
在 Jupyter Notebooks 中,解决这个问题的一种简洁方法是使用 markdown:
from IPython.display import Markdown, display
def printmd(string):
display(Markdown(string))
然后做类似的事情:
printmd("**bold text**")
当然,这对于粗体、斜体等非常有用,但 markdown 本身并没有实现颜色。但是,您可以将 html 放在 markdown 中,并得到如下内容:
printmd("<span style='color:red'>Red text</span>")
您也可以将它包装在 printmd
函数中:
def printmd(string, color=None):
colorstr = "<span style='color:{}'>{}</span>".format(color, string)
display(Markdown(colorstr))
然后做一些很酷的事情,比如
printmd("**bold and blue**", color="blue")
对于颜色,您也可以使用十六进制表示法(例如,color = "#00FF00"
表示绿色)
澄清一下,尽管我们使用 markdown,但这是一个代码单元格:您可以执行以下操作:
for c in ('green', 'blue', 'red', 'yellow'):
printmd("Writing in {}".format(c), color=c)
当然,这种方法的一个缺点是依赖于在 Jupyter notebook 中。
关于python - 在 ipython qtconsole 中打印粗体、彩色等文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23271575/