sys.stdout.write()
が好ましい状況はありますかprint
?
(例:パフォーマンスの向上、より意味のあるコード)
ベストアンサー1
print
は、入力をフォーマットする(変更可能だが、デフォルトでは引数の間にスペースが入り、最後に改行が入る)だけの薄いラッパーで、指定されたオブジェクトの write 関数を呼び出します。デフォルトではこのオブジェクトは ですsys.stdout
が、「chevron」形式を使用してファイルを渡すことができます。例:
print >> open('file.txt', 'w'), 'Hello', 'World', 2+3
見る:https://docs.python.org/2/reference/simple_stmts.html?highlight=print#the-print-statement
Python 3.x では関数になりますが、引数のおかげでprint
それ以外のものを渡すことも可能です。sys.stdout
file
print('Hello', 'World', 2+3, file=open('file.txt', 'w'))
見るhttps://docs.python.org/3/library/functions.html#print
Python 2.6以降では、print
は依然として文ですが、関数として使用できます。
from __future__ import print_function
更新: Bakuriu は、print 関数と print ステートメント (より一般的には関数とステートメント) の間には小さな違いがあることを指摘するコメントを残しました。
引数の評価時にエラーが発生した場合:
print "something", 1/0, "other" #prints only something because 1/0 raise an Exception
print("something", 1/0, "other") #doesn't print anything. The function is not called