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

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

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


在Python 3中,可以使用print函数的sep=和end=参数:

要不在字符串末尾添加换行符,请执行以下操作:

print('.', end='')

要在要打印的所有函数参数之间不添加空格,请执行以下操作:

print('a', 'b', 'c', sep='')

您可以将任何字符串传递给任一参数,并且可以同时使用两个参数。

如果缓冲有问题,可以通过添加flush=True关键字参数来刷新输出:

print('.', end='', flush=True)

Python 2.6和2.7

从Python 2.6中,您可以使用__future__模块从Python 3导入打印函数:

from __future__ import print_function

这允许您使用上面的Python3解决方案。

但是,请注意,flush关键字在从Python 2中的__future__导入的打印函数版本中不可用;它只适用于Python 3,更具体地说是3.3及更高版本。在早期版本中,您仍然需要通过调用sys.stdout.flush()来手动刷新。您还需要在执行此导入的文件中重写所有其他打印语句。

或者可以使用sys.stdout.write()

import sys
sys.stdout.write('.')

您可能还需要致电

sys.stdout.flush()

以确保立即刷新stdout。


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

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

输出:

你好,你好

分隔符也有sep:

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

输出:

你好你好

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

from __future__ import print_function

注意:这个问题的标题以前类似于“How to printf in Python”

由于人们可能会根据标题来这里寻找它,Python也支持printf样式替换:

>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
...     print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three

而且,您可以方便地相乘字符串值:

>>> print "." * 10
..........

如何在同一行打印:

import sys
for i in xrange(0,10):
   sys.stdout.write(".")
   sys.stdout.flush()

为Python 2.6+使用Python 3样式打印函数(它还将打破同一文件中任何现有的带关键字的打印语句)。

# For Python 2 to use the print() function, removing the print keyword
from __future__ import print_function
for x in xrange(10):
    print('.', end='')

为了不破坏所有Python 2打印关键字,请创建一个单独的printf.py文件:

# printf.py

from __future__ import print_function

def printf(str, *args):
    print(str % args, end='')

然后,在文件中使用它:

from printf import printf
for x in xrange(10):
    printf('.')
print 'done'
#..........done

显示printf样式的更多示例:

printf('hello %s', 'world')
printf('%i %f', 10, 3.14)
#hello world10 3.140000

我最近也有同样的问题。。。

我通过以下方式解决了这个问题:

import sys, os

# Reopen standard output with "newline=None".
# in this mode,
# Input:  accepts any newline character, outputs as '\n'
# Output: '\n' converts to os.linesep

sys.stdout = os.fdopen(sys.stdout.fileno(), "w", newline=None)

for i in range(1,10):
    print(i)

这在Unix和Windows上都有效,但我还没有在Mac OS X上测试过。


对于Python 2和更早版本,它应该像Re中描述的那样简单:没有CR如何打印?作者:Guido van Rossum(意译):

是否可以打印某些内容,但不能自动生成是否附加回车?

是的,在要打印的最后一个参数后附加逗号。例如,此循环将数字0..9打印在由空格分隔的行上。请注意添加最后一行的无参数“print”:

>>> for i in range(10):
...     print i,
... else:
...     print
...
0 1 2 3 4 5 6 7 8 9
>>>

您可以在Python 3中执行以下操作:

#!usr/bin/python

i = 0
while i<10 :
    print('.', end='')
    i = i+1

并使用python filename.py或python3 filename.py。


在Python2.x中,您可以在print函数的末尾添加,这样它就不会在新行上打印了。


for i in xrange(0,10): print '\b.',

这在2.7.8和2.5.2(分别为焓盖和OS X终端)中都有效——不需要模块导入或时间旅行。


莱诺满足了我的要求。我在搜索“python suppress newline”时发现了这篇文章。我正在树莓派上使用IDLE 3为PuTTY开发Python 3.2。

我想在PuTTY命令行上创建一个进度条。我不希望页面滚动。我想要一条水平线,让用户放心,不要担心程序没有停止,也没有在一个快乐的无限循环中被送去吃午饭,以此恳求“离开我吧,我做得很好,但这可能需要一些时间。”交互式消息-如文本中的进度条。

打印('Shamming for',search_string,'\b!.001',end='')通过准备下一次屏幕写入来初始化消息,这将打印三个退格作为⌫\9003;\9003搓出,然后打印一个句点,删除“001”并延长句点行。

search_string鹦鹉学舌用户输入后,\b!修剪search_string文本的感叹号,使其位于print()强制的空格上方,并正确放置标点符号。然后是空格和我正在模拟的“进度条”的第一个“点”。

不必要的是,消息也会以页码开头(格式为三,带前导零),以通知用户正在处理进度,这也将反映我们稍后将在右侧构建的周期数。

import sys

page=1
search_string=input('Search for?',)
print('Skimming for', search_string, '\b! .001', end='')
sys.stdout.flush() # the print function with an end='' won't print unless forced
while page:
    # some stuff…
    # search, scrub, and build bulk output list[], count items,
    # set done flag True
    page=page+1 #done flag set in 'some_stuff'
    sys.stdout.write('\b\b\b.'+format(page, '03')) #<-- here's the progress bar meat
    sys.stdout.flush()
    if done: #( flag alternative to break, exit or quit)
        print('\nSorting', item_count, 'items')
        page=0 # exits the 'while page' loop
list.sort()
for item_count in range(0, items)
    print(list[item_count])

#print footers here
if not (len(list)==items):
    print('#error_handler')

进度条肉在sys.stdout.write('\b\b\b.'+格式(第页,“03”)行中。首先,要向左擦除,它将光标备份到三个数字字符上,并将“\b\b\b”作为“⌫\9003 \9003;”,然后删除一个新的句点以添加到进度条长度。然后,它将写入到目前为止已完成的页面的三位数。因为sys.stdout.write()等待满缓冲区或输出通道关闭,所以sys.stdut.flush()强制立即写入。sys.stdout.flush()内置在打印结束()中,该结束被打印(txt,end='')绕过。然后,代码循环执行普通的时间密集型操作,而不打印任何内容,直到它返回此处,将三位数字擦回去,添加一个句点,然后再次写入三位数字,递增。

擦除和重写的三个数字绝非必要——这只是一个繁荣的例子,它是sys.stdout.write()与print()的对比。你也可以很容易地用句点填充,并忘记三个奇怪的反斜杠-b⌫退格(当然,也不写格式化的页计数),只需每次打印一个句点条,而不用空格或换行,只需使用sys.stdout.write('.');sys.stdout.flush()对。

请注意,Raspberry Pi IDLE 3 Python外壳不将退格视为⌫rubout,而是打印一个空格,创建一个明显的分数列表。


使用functools.partal创建名为printf的新函数:

>>> import functools

>>> printf = functools.partial(print, end="")

>>> printf("Hello world\n")
Hello world

用默认参数包装函数是一种简单的方法。


Python 3:

print('.', end='')

Python 2.6+:

from __future__ import print_function # needs to be first statement in file
print('.', end='')

Python<=2.5:

import sys
sys.stdout.write('.')

如果每次打印后都有多余的空间,在Python 2中:

print '.',

Python 2中的误导-避免:

print('.'), # Avoid this if you want to remain sane
# This makes it look like print is a function, but it is not.
# This is the `,` creating a tuple and the parentheses enclose an expression.
# To see the problem, try:
print('.', 'x'), # This will print `('.', 'x') `

你想在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

您可以尝试:

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')

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

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

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


在Python 3+中,print是一个函数。当你打电话时

print('Hello, World!')

Python将其翻译为

print('Hello, World!', end='\n')

你可以随心所欲。

print('Hello, World!', end='')
print('Hello, World!', end=' ')

你会注意到以上所有答案都是正确的。但我想做一个捷径,始终在结尾处写入“end=''”参数。

您可以定义如下函数

def Print(*args, sep='', end='', file=None, flush=False):
    print(*args, sep=sep, end=end, file=file, flush=flush)

它将接受所有数量的参数。甚至它也会接受所有其他参数,如file、flush等,并使用相同的名称。


您不需要导入任何库。只需使用删除字符:

BS = u'\0008' # The Unicode point for the "delete" character
for i in range(10):print(BS + "."),

这将删除换行符和空格(^_^)*。


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

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

您可以访问此链接。


或具有如下功能:

def Print(s):
    return sys.stdout.write(str(s))

现在:

for i in range(10): # Or `xrange` for the Python 2 version
    Print(i)

输出:

0123456789

 for i in range(0, 5): #setting the value of (i) in the range 0 to 5 
     print(i)

上述代码给出以下输出:

 0    
 1
 2
 3
 4

但是,如果您想在一条直线上打印所有这些输出,那么您需要做的就是添加一个名为end()的属性来打印。

 for i in range(0, 5): #setting the value of (i) in the range 0 to 5 
     print(i, end=" ")

输出:

 0 1 2 3 4

不仅是空格,还可以为输出添加其他结尾。例如

 for i in range(0, 5): #setting the value of (i) in the range 0 to 5 
     print(i, end=", ")

输出:

 0, 1, 2, 3, 4, 

记得:

 Note: The [for variable in range(int_1, int_2):] always prints till the variable is 1

 less than it's limit. (1 less than int_2)

蟒蛇3:

print('Hello',end='')

例子:

print('Hello',end=' ')
print('world')

输出:你好,世界

此方法在提供的文本之间添加sperator:

print('Hello','world',sep=',')

输出:你好,世界


只需使用end=“”或sep=“”

>>> for i in range(10):
        print('.', end = "")

输出:

.........

只需使用end=''

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

# aaaaa

这里有三个代码供您选择:

print("".join(["." for i in range(4)]))

or

print("." + "." + "." + ".")

or

print(".", ".", ".", ".", sep="")