在 Python 中,
在 2.x 版本中,
參數選項
可以用 help(print)
來查看 print
函數的參數解釋。
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
- value: 打印的值,可多個
- file: 輸出流,默認是
sys.stdout
- sep: 多個值之間的分隔符
- end: 結束符,默認是換行符
\n
- flush: 是否強制刷新到輸出流,默認否
能打印任意數據
- 打印數字、字符串、布爾值
print(1024, 10.24, 'hello', False)
# 1024 10.24 hello False
- 打印列表
print([1, 2, 3])
# [1, 2, 3]
- 打印元組
print((1, 2, 3))
# (1, 2, 3)
- 打印字典
print({'name': 'hello', 'age': 18})
# {'name': 'hello', 'age': 18}
- 打印集合
print({1, 2, 3})
# {1, 2, 3}
- 打印對象
class Demo:
pass
demo = Demo()
print(demo)
# <__main__.Demo object at 0x1005bae80>
分隔符
默認分隔符是空格,sep
參數可以修改。
print(1, 2, 3, sep='-')
# 1-2-3
結束符
默認結束符是行號,end
參數可以修改。
print('第一行', end='-')
print('第二行')
# 第一行-第二行
輸出重定向
默認情況下,print
函數會將內容打印輸出到標准輸出流(即 sys.stdout),可以通過 file 參數自定義輸出流。
with open('data.log', 'w') as fileObj:
print('hello world!', file=fileObj)
此時,不會有任何標准輸出,但對應的文件中已經有了內容。
我們也可以輸出到錯誤輸出流,例如:
import sys
print('hello world!', file=sys.stderr)