python2.x 与 python3.x 中print函数

本文介绍了Python2.x和Python3.x中print函数的差异。在Python3中,通过`print("*", end="")`避免换行,而在Python2.x中,可以使用`from __future__ import print_function`来实现相同效果。另外,Python2中通过在print后加逗号来消除换行,但会产生额外空格。正确输出星号无多余空格的Python2代码有两种形式。" 113680752,10541678,Qt QML ListView 鼠标交互实现,"['Qt开发', 'QML界面', '用户交互']

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

例如输出

*
**
***
****
*****
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  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值