在python中我們偶爾會用到輸出不換行的效果,python2中使用逗號,即可,而python3中使用end=''來實現(xiàn)的,這里簡單為大家介紹一下,需要的朋友可以參考下
python輸出不換行
Python2的寫法是:
1
|
print 'hello' , |
Python3的寫法是:
1
|
print ( 'hello' , end = '') |
對于python2和python3都兼容的寫法是:
1
2
|
from __future__ import print_function print ( 'hello' , end = '') |
python ,end=''備注
就是打印之后不換行。在Python2.7中使用“,”
下面是2.7的例子:
1
2
3
|
def test(): print 'hello' , print 'world' |
輸出 hello world
hello后面沒有換行。
如果是python3以后的版本中則用end=‘ '
在python3.x之后,可以在print()之中加end=""來解決,可以自定義結(jié)尾字符
1
2
|
print ( 'hello' ,end = ' ' ) print ( 'world' ) |
end后面的內(nèi)容就是一個空格,要不hello world就變成helloworld了。
繼續(xù)看下面的實例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
'end=' 意思是不換行,例如: temp = input ( '輸入一個整數(shù)' ) i = int (temp) while i : print ( '*' ) i = i - 1 輸入 4 結(jié)果是: * * * * 更改代碼: temp = input ( '輸入一個整數(shù)' ) i = int (temp) while i : print ( '*' ,end = '') i = i - 1 輸入 4 結(jié)果是: * * * * |