python 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.
  • 在python中,print默認向屏幕輸出指定的文字,例如:

    >>>print('hello,world')
    hello world

  • print的完整格式為print(objects,sep,end,file,flush),其中后面4個為可選參數

    1. sep
      在輸出字符串之間插入指定字符串,默認是空格,例如:
      >>>print("a","b","c",sep="**")
      a**b**c
    2. end
      print輸出語句的結尾加上指定字符串,默認是換行(\n),例如:
      >>>print("a",end="$")
      a$
      print默認是換行,即輸出語句后自動切換到下一行,對於python3來說,如果要實現輸出不換行的功能,那么可以設置end=''(python2可以在print語句之后加“,”實現不換行的功能)
    3. file
      將文本輸入到file-like對象中,可以是文件,數據流等等,默認是sys.stdout
      >>>f = open('abc.txt','w')
      >>>print('a',file=f)
    4. flush
      flush值為True或者False,默認為Flase,表示是否立刻將輸出語句輸入到參數file指向的對象中(默認是sys.stdout)例如:
      >>>f = open('abc.txt','w')
      >>>print('a',file=f)
      可以看到abc.txt文件這時為空,只有執行f.close()之后才將內容寫進文件。
      如果改為:
      >>>print('a',file=f,flush=True)
      則立刻就可以看到文件的內容


免責聲明!

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



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