Python內置函數(50)——print


英文文檔:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Print objects to the text stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

 

說明:

  1. 用於對象打印輸出。通過命名參數sep來確定多個輸出對象的分隔符(默認' '),通過命名參數end確定輸出結果的結尾(默認'\n'),通過命名參數file確定往哪里輸出(默認sys.stdout),通過命名參數fiush確定輸出是否使用緩存(默認False)。

>>> print(1,2,3)
1 2 3
>>> print(1,2,3,sep = '+')
1+2+3
>>> print(1,2,3,sep = '+',end = '=?')
1+2+3=?

  2. sep、end、file、flush都必須以命名參數方式傳參,否則將被當做需要輸出的對象了。

>>> print(1,2,3,'+','=?')
1 2 3 + =?

  3. sep和end參數必須是字符串;或者為None,為None時意味着將使用其默認值。

>>> print(1,2,3,sep = 97,end = 100)
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    print(1,2,3,sep = 97,end = 100)
TypeError: sep must be None or a string, not int
>>> print(1,2,3,sep = None,end = None)
1 2 3

  4. 不給print傳遞任何參數,將只輸出end參數的默認值。

>>> print()

>>> print(end = 'by 2016')
by 2016

  5. file參數必須是一個含有write(string) 方法的對象。

>>> class A:
    @staticmethod    
    def write(s):
        print(s)

        
>>> a = A()
>>> print(1,2,3,sep = '+',end = '=?',file = a)
1
+
2
+
3
=?

 


免責聲明!

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



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