Python2 与 Python3 print不换行 (print() 函数中添加 end="" 参数)

Python2 与 Python3 print不换行 (print() 函数中添加 end="" 参数)

本文主要介绍在 Python2 与 Python3 下 print 实现不换行的效果。
Python 3.x
在 Python 3.x 中,我们可以在 print() 函数中添加 end="" 参数,这样就可以实现不换行效果。
在 Python3 中, print 函数的参数 end 默认值为 "\n",即end="\n",表示换行,给 end 赋值为空, 即end="",就不会换行了,例如:

Python3.x 实例
print('这是字符串,', end="")
print('这里的字符串不会另起一行')

执行以上代码,输出结果为:
这是字符串,这里的字符串不会另起一行

图片.png

Python3.x运行:

x="a"
y="b"
# 换行输出
print(x)
print(y)
print ('_______')
#
print(x),
print(y),
# 不换行输出
print(x,y)

图片.png

x="a"
y="b"
# 换行输出
print(x)
print(y)
print ('___1____')
#
print(x, end=""),
print(y, end=""),
# 不换行输出
print(x,y)
print ('___2____')
#
print(x, end=""),
print(y, end=""),
# 不换行输出
print(x,end=y)

图片.png


end="" 可以设置一些特色符号或字符串:

实例
print('12345', end="")
print('6789')
print('12345', end=" ")  # 设置空格
print('6789')
print('admin', end="@")  # 设置符号
print('zh-cjh.com')
print('珠海', end="陈坚浩  ")  # 设置字符串
print('个人博客')
执行以上代码,输出结果为:
123456789
12345 6789
admin@zh-cjh.com
珠海陈坚浩  个人博客

图片.png


Python 2.x
在 Python 2.x中, 可以使用逗号 , 来实现不换行效果:
Python2.x 实例
#!/usr/bin/python
# -*- coding: UTF-8 -*-
print "这是字符串,",         # 末尾添加逗号
print "这里的字符串不会另起一行"
# print 带括号
print ("这是字符串,"),        # 末尾添加逗号
print ("这里的字符串不会另起一行")

执行以上代码,输出结果为:
这是字符串, 这里的字符串不会另起一行
这是字符串, 这里的字符串不会另起一行

如果有变量,我们可以在逗号 , 后面直接添加变量:
Python2.x 实例
#!/usr/bin/python
# -*- coding: UTF-8 -*-
x= 2
print "数字为:", x

执行以上代码,输出结果为:
字为: 2

注意:这种输出方法,在 , 末尾会有一个空格输出,类似于使用了 Python 3 的 end=" "。


Python2.x 与 Python3.x 兼容模式
如果 Python2.x 版本想使用 Python3.x 的 print 函数,可以导入 __future__ 包,该包禁用 Python2.x 的 print 语句,采用 Python3.x 的 print 函数。

以下代码在 Python2.x 与 Python3.x 都能正确执行:
Python2.x 实例
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import print_function
print('12345', end=" ")  # 设置空格
print('6789')
print('admin', end="@")  # 设置符号
print('zh-cjh.com')
print('Google ', end="zh-cjh ")  # 设置字符串
print('Taobao')

注:Python3.x 与 Python2.x 的许多兼容性设计的功能可以通过 __future__ 这个包来导入。

1、本站资源长期持续更新。
2、本资源基本为原创,部分来源其他付费资源平台或互联网收集,如有侵权请联系及时处理。
3、本站大部分文章的截图来源实验测试环境,请不要在生产环境中随意模仿,以免带来灾难性后果。

转载请保留出处:  www.zh-cjh.com珠海陈坚浩博客 » Python2 与 Python3 print不换行 (print() 函数中添加 end="" 参数)

作者: cjh


手机扫一扫,手机上查看此文章:

一切源于价值!

其他 模板文件不存在: ./template/plugins/comment/pc/index.htm

未雨绸缪、居安思危!

数据安全、有备无患!

注意操作、数据无价!

一切源于价值!