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 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)

參考資料


個人博客同步地址:
https://shockerli.net/post/python3-print/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM