考虑在Python中使用print的以下示例:

>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .

在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?


当前回答

Python 3.x中的print函数有一个可选的结束参数,可用于修改结束字符:

print("HELLO", end="")
print("HELLO")

输出:

你好,你好

分隔符也有sep:

print("HELLO", "HELLO", "HELLO", sep="")

输出:

你好你好

如果您想在Python2.x中使用它,只需在文件开头添加:

from __future__ import print_function

其他回答

只需使用end=''

for i in range(5):
  print('a',end='')

# aaaaa

其中许多答案似乎有点复杂。在Python 3.x中,您只需执行以下操作:

print(<expr>, <expr>, ..., <expr>, end=" ")

end的默认值为“\n”。我们只是将其更改为空格,或者您也可以使用end=“”(无空格)来执行printf通常所做的操作。

您可以尝试:

import sys
import time
# Keeps the initial message in buffer.
sys.stdout.write("\rfoobar bar black sheep")
sys.stdout.flush()
# Wait 2 seconds
time.sleep(2)
# Replace the message with a new one.
sys.stdout.write("\r"+'hahahahaaa             ')
sys.stdout.flush()
# Finalize the new message by printing a return carriage.
sys.stdout.write('\n')

你想在for循环中打印一些东西;但你不希望每次都用新的行打印。。。

例如:

 for i in range (0,5):
   print "hi"

 OUTPUT:
    hi
    hi
    hi
    hi
    hi

但你希望它像这样打印:嗨嗨嗨嗨对吗????

只需在打印“hi”后添加逗号。

例子:

for i in range (0,5):
    print "hi",

输出:

hi hi hi hi hi

通常,有两种方法可以做到这一点:

在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),

您可以访问此链接。