Python: 消除print的自動換行

小威威__發表於2015-12-11

Python: 消除print換行

標籤:python print \n

by 小威威


對於python2.X,要消除print的自動換行,只需在print尾部加上一個逗號”,”,但是這一做法在python3.X就不適用了,這是為什麼呢?我們可以在互動式的環境下輸入help(print),查詢print的原理和使用方法。

Help on built-in function print in module builtins:

print(…)
print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

appledeMacBook-Pro-2:Desktop apple$ python3
Python 3.5.0 (v3.5.0:374f501f4567, Sep 12 2015, 11:00:19) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help(print)
Help on built-in function print in module builtins:

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.
(END) 

注意看這一句:

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

這一句說明在python3中print是一個函式,對於函式,其形參中有預設引數和關鍵引數。我們發現,在結尾處出現了end = ‘\n’,說明print是以\n結束的,end是預設引數。只要我們在print中將預設引數的值改為空或者空格,就能實現不換行。

舉個栗子:

#!/usr/bin/python3
# Filename: using_list.py

# This is my shopping list

shoplist = ['apple', 'mango', 'carrot', 'banana']
print ('These items are:')
for i in shoplist:
    print (i,end=' ')
# End

輸出結果如下:

These items are:
apple mango carrot banana 

以上內容皆為本人觀點,歡迎大家提出批評和指導,我們一起探討。


相關文章