本文主�介�在 Python2 与 Python3 下 print 实现��行的效果。

Python 3.x

在 Python 3.x 中,我们�以在 print() 函数中添加 end="" �数,这样就�以实现��行效果。

在 Python3 中, print 函数的�数 end 默认值为 "\n",�end="\n",表示�行,给 end 赋值为空, �end="",就�会�行了,例如:

Python3.x 实例

print('这是字符串,', end="")
print('这里的字符串�会�起一行')

执行以上代�,输出结果为:

这是字符串,这里的字符串�会�起一行

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

实例

print('12345', end=" ")  # 设置空格
print('6789')

print('admin', end="@")  # 设置符å�·
print('runoob.com')

print('Google ', end="Runoob ")  # 设置字符串
print('Taobao')

执行以上代�,输出结果为:

12345 6789
admin@runoob.com
Google Runoob Taobao

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('runoob.com')

print('Google ', end="Runoob ")  # 设置字符串
print('Taobao')

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