python2.x 与 python3.x 中print函数

翻了好几个博客都没找到,还是知乎强大啊!!!!

例如输出

*
**
***
****
*****
python中,在print后面加一个逗号,虽然没有换行,但是会输出多余的一个空格

在print后面增加end="",即print("*",end=""),是python3中的内容,要在2.X中使用,需要在代码第一行增加 from __future__ import print_functio



在python2中,在print最后增加一个逗号,来消除换换行,星号之间会有多余的空格,代码如下:

*
* *
* * *
* * * *
* * * * *


#from __future__ import print_function
i = 1

while i <= 5:
	j = 1
	while j <= i:
		if j < i:
			print "*",
		else:
			print("*")
		j += 1
	#print
	i += 1



在python2中,正确的代码如下:

from __future__ import print_function
i = 1

while i <= 5:
	j = 1
	while j <= i:
		
		if j < i:
			#输出字符 "*"
			print("*",end="")
		else:
			print("*")
		j += 1
	#print
	i += 1


或者: 单纯的输出换行是print(“”)

from __future__ import print_function  
i = 1  
  
while i <= 5:  
    j = 1  

    while j <= i:  
        print("*",end="")  
        j += 1 
    print("")
    
    i += 1  



你可能感兴趣的:(python)