考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
当前回答
通常,有两种方法可以做到这一点:
在Python3.x中无换行打印
在print语句后不追加任何内容,并使用end=“”删除“\n”,如下所示:
>>> print('hello')
hello # Appending '\n' automatically
>>> print('world')
world # With previous '\n' world comes down
# The solution is:
>>> print('hello', end='');print(' world'); # End with anything like end='-' or end=" ", but not '\n'
hello world # It seems to be the correct output
循环中的另一个示例:
for i in range(1,10):
print(i, end='.')
在Python2.x中无换行打印
添加尾随逗号表示:打印后,忽略\n。
>>> print "hello",; print" world"
hello world
循环中的另一个示例:
for i in range(1,10):
print "{} .".format(i),
您可以访问此链接。
其他回答
其中许多答案似乎有点复杂。在Python 3.x中,您只需执行以下操作:
print(<expr>, <expr>, ..., <expr>, end=" ")
end的默认值为“\n”。我们只是将其更改为空格,或者您也可以使用end=“”(无空格)来执行printf通常所做的操作。
Python 3.x中的print函数有一个可选的结束参数,可用于修改结束字符:
print("HELLO", end="")
print("HELLO")
输出:
你好,你好
分隔符也有sep:
print("HELLO", "HELLO", "HELLO", sep="")
输出:
你好你好
如果您想在Python2.x中使用它,只需在文件开头添加:
from __future__ import print_function
您不需要导入任何库。只需使用删除字符:
BS = u'\0008' # The Unicode point for the "delete" character
for i in range(10):print(BS + "."),
这将删除换行符和空格(^_^)*。
你会注意到以上所有答案都是正确的。但我想做一个捷径,始终在结尾处写入“end=''”参数。
您可以定义如下函数
def Print(*args, sep='', end='', file=None, flush=False):
print(*args, sep=sep, end=end, file=file, flush=flush)
它将接受所有数量的参数。甚至它也会接受所有其他参数,如file、flush等,并使用相同的名称。
在Python 3+中,print是一个函数。当你打电话时
print('Hello, World!')
Python将其翻译为
print('Hello, World!', end='\n')
你可以随心所欲。
print('Hello, World!', end='')
print('Hello, World!', end=' ')