Python 2.x下的print語句在輸出字符串之后會默認換行,如果不希望換行,只要在語句最后加一個“,”即可。但是在Python 3.x下,print()變成內置函數,加“,”的老方法就行不通了。
查詢Python的Library Reference>Built-in Functions,找到如下條目:
“print([object, ...], *, sep=' ', end='\n', file=sys.stdout)
-
Print object(s) to the stream file, separated by sep and followed by end. sep, endand 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 objectis 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. ”
其中,sep=''和end='\n'均是print()的關鍵參數,sep的默認值為空,end默認值為換行符,這就是print()在輸出后默認換行的原因。相應的,解決辦法就是對end賦值:print(something, something,.., end=''),使end值為空,這個換行就消除了。
原文地址:http://wpp9977777.blog.163.com/blog/static/46251007201192905622402/
