python3 打印_Python 3 进阶 —— print 打印和输出
在 Python 中,print 可以打印所有變量數據,包括自定義類型。
在 2.x 版本中,print 是個語句,但在 3.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>
分隔符
默認分隔符是空格,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)
參考資料
總結
以上是生活随笔為你收集整理的python3 打印_Python 3 进阶 —— print 打印和输出的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为将再发新款半入耳旗舰产品,用水滴造型
- 下一篇: python中curve fit_在py