您的位置:首页 > 编程语言 > Python开发

python2.x 与 python3.x 中print函数

2017-11-19 12:05 351 查看
翻了好几个博客都没找到,还是知乎强大啊!!!!

例如输出

*
**
***
****
*****
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: