天天看點

Python學習:001——print函數

引言

雖然用python寫過不少腳本了,但總感覺串不起來的樣子。整好在github上看到一個100天學python的文章(https://github.com/jackfrued/Python-100-Days),閑來無事,每天重溫一下吧,順便記錄下來。有錯誤的,歡迎指正啦。

一、print()函數

python3中,print變成了函數。

print('hello, world!')
print("你好,世界!")
print('你好', '世界')
print('hello', 'world', sep=', ', end='!')
print('goodbye, world', end='!\n')
           

1.print('hello, world!')

print函數裡,字元串需要用單引号對,或雙引号對,或三引号對括起來。三引号對可以跨行,當然也可以用反斜杠(\)來跨行。

print("hello, world!")

>>>hello, world!
           

2.print("你好, 世界!")

print函數裡,中文字元串輸出同英文字元串輸出。由于python3字元編碼格式已經由python2裡的unicode編碼集改為python3的utf-8編碼集,是以不會出現python2裡令人頭大的編碼問題。

print("你好,世界!")
print(u"你好,世界!")  #python2寫法

>>>你好,世界!
           

3.print("你好", “世界”)

print函數裡,也支援分開寫,同上,主要用途應該是友善下面這個寫法,或者輸出太長的時候,友善代碼整潔吧。

print('你好', "世界")

>>>你好 世界
           

4.print('hello', 'world', sep=', ', end='!')

sep(separate)本意就是分開,就是說輸出的兩個詞語中間用逗号隔開,結尾“!”。

print('hello', 'world', sep=', ', end='!')

>>>hello, world!
           

5.print('goodbye, world', end='!\n')

'\n'為轉義字元,同其他語言一樣,換行的意思。

print('goodbye, world', end='!\n')

>>>goodbye, world!
>>>
           

6.總結

來自builtins.py:以下為print函數的源代碼。也可以通過help(print)檢視函數參數說明。
           
def print(self, *args, sep=' ', end='\n', file=None): # known special case of 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.
    """