Python 中的输出替代方案
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2570269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Output alternatives in Python
提问by Eli Bendersky
Is there any alternatives to the print statement for output in Python.
Also, how can I format my output text to be color-coded?
Python 中输出的打印语句是否有任何替代方法。
另外,如何将我的输出文本格式化为彩色编码?
I'm a beginner programmer, pretty new to it.
Thanks
我是一个初学者程序员,对它很陌生。
谢谢
回答by Eli Bendersky
sys.stdout.write()
Is one alternative. You can also write to sys.stderr
. Personally, I use sys.stdout
when I need to pass a generic "stream" to some function that will write to it. And open file is a stream, and sys.stdout
is a stream. This way my function can be parametrized to write either to output or to file.
是一种选择。您也可以写入sys.stderr
.就个人而言,sys.stdout
当我需要将通用“流”传递给将写入它的某个函数时,我会使用它。而打开的文件是一个流,而且sys.stdout
是一个流。这样我的函数可以被参数化以写入输出或文件。
I also find sys.stdout.write
more convenient than print
for printing many things to a single line, as I find the ending comma syntax of print
for suppressing the newline ugly and inconvenient.
我还发现sys.stdout.write
比print
将许多内容打印到一行更方便,因为我发现print
用于抑制换行符的结尾逗号语法丑陋且不方便。
Regarding printing to the terminal in colors, see this other SO discussion.
关于以颜色打印到终端,请参阅其他 SO 讨论。
回答by anijhaw
You can use PrettyPrintfor print data
您可以使用PrettyPrint打印数据