C中的示例:
for (int i = 0; i < 4; i++)
printf(".");
输出:
....
在 Python 中:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在 Python 中,print
将添加一个 \n
或空格。我怎样才能避免这种情况?我想知道如何将字符串“附加”到 stdout
。
print("." * 10)
?
在 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__
module 从 Python 3 导入 print
函数:
from __future__ import print_function
它允许您使用上面的 Python 3 解决方案。
但是,请注意 flush
关键字在 Python 2 中从 __future__
导入的 print
函数版本中不可用;它仅适用于 Python 3,更具体地说是 3.3 及更高版本。在早期版本中,您仍需要通过调用 sys.stdout.flush()
手动刷新。您还必须在执行此导入的文件中重写所有其他打印语句。
或者您可以使用 sys.stdout.write()
import sys
sys.stdout.write('.')
您可能还需要致电
sys.stdout.flush()
以确保立即刷新 stdout
。
对于 Python 2 及更早版本,它应该像 Guido van Rossum 在 Re: How does one print without a CR? 中描述的一样简单(释义):
是否可以打印一些东西,但不能自动附加回车符?
是的,在要打印的最后一个参数之后附加一个逗号。例如,此循环在由空格分隔的行上打印数字 0..9。请注意添加最终换行符的无参数“打印”:
>>> for i in range(10):
... print i,
... else:
... print
...
0 1 2 3 4 5 6 7 8 9
>>>
0123456..
注意:这个问题的标题曾经类似于“如何在 Python 中 printf”
由于人们可能会根据标题来这里寻找它,因此 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
..........
对 Python 2.6+ 使用 Python 3 风格的 print 函数(它还会破坏同一文件中任何现有的关键字 print 语句)。
# 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
for i in xrange(0,10):
sys.stdout.write(".")
sys.stdout.flush()
Python 3.x 中的 print
函数有一个可选的 end
参数,可让您修改结束字符:
print("HELLO", end="")
print("HELLO")
输出:
你好你好
还有 sep
用于分隔符:
print("HELLO", "HELLO", "HELLO", sep="")
输出:
你好你好你好
如果您想在 Python 2.x 中使用它,只需在文件开头添加:
from __future__ import print_function
使用 functools.partial 创建一个名为 printf 的新函数:
>>> import functools
>>> printf = functools.partial(print, end="")
>>> printf("Hello world\n")
Hello world
这是用默认参数包装函数的简单方法。
otherfunction = function(1)
只会存储 function(1)
的结果,而不是将 otherfunction
变成包装器。谢谢!
在 Python 3+ 中,print
是一个函数。你打电话时
print('Hello, World!')
Python 将其翻译为
print('Hello, World!', end='\n')
您可以将 end
更改为您想要的任何内容。
print('Hello, World!', end='')
print('Hello, World!', end=' ')
在 Python 2.x 中,您只需在 print
函数的末尾添加 ,
,它就不会在新行上打印。
蟒蛇 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') `
一般来说,有两种方法可以做到这一点:
在 Python 3.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='.')
在 Python 2.x 中不带换行符打印
添加尾随逗号表示:打印后,忽略 \n
。
>>> print "hello",; print" world"
hello world
循环中的另一个示例:
for i in range(1,10):
print "{} .".format(i),
您可以访问此link。
end=" "
例如: print('hello', end='' ");print('world')
print 'hello' ;print'there'
你可以试试:
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')
我最近遇到了同样的问题...
我通过这样做解决了它:
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 上测试过。
sys.__stdout__
您可以在 Python 3 中执行相同的操作,如下所示:
#!usr/bin/python
i = 0
while i<10 :
print('.', end='')
i = i+1
并使用 python filename.py
或 python3 filename.py
执行它。
其中许多答案似乎有点复杂。在 Python 3.x 中,您只需执行以下操作:
print(<expr>, <expr>, ..., <expr>, end=" ")
end 的默认值为 "\n"
。我们只是将其更改为空格,或者您也可以使用 end=""
(无空格)来执行 printf
通常执行的操作。
你想在for循环中打印一些东西;但是您不希望它每次都在新行中打印...
例如:
for i in range (0,5):
print "hi"
OUTPUT:
hi
hi
hi
hi
hi
但是您希望它像这样打印: hi hi hi hi hi hi 对吗????
只需在打印“hi”后添加一个逗号。
例子:
for i in range (0,5):
print "hi",
输出:
hi hi hi hi hi
您会注意到以上所有答案都是正确的。但我想创建一个捷径,总是在最后写入“end=''”参数。
您可以定义一个函数,例如
def Print(*args, sep='', end='', file=None, flush=False):
print(*args, sep=sep, end=end, file=file, flush=flush)
它将接受所有数量的参数。即使它会接受所有其他参数,如文件、刷新等,并且具有相同的名称。
*arg
处于开头(python 2.7),并将它放在最后确实运行了,但没有完全正确地工作。我定义了一个只使用 Print(*args)
的函数,然后使用 sep='', end=''
调用 print。现在它可以按我的意愿工作。所以有人赞成这个想法。
lenooh satisfied 我的查询。我在搜索“python suppress newline”时发现了这篇文章。我在 Raspberry Pi 上使用 IDLE 3 为 PuTTY 开发 Python 3.2。
我想在 PuTTY 命令行上创建一个进度条。我不希望页面滚动。我想要一条水平线来让用户放心,让用户不会因为程序没有停止运行,也没有在快乐的无限循环中被送去吃午饭而感到害怕——作为请求‘别管我,我做得很好,但是这个可能需要一些时间。交互式消息 - 就像文本中的进度条。
print('Skimming for', search_string, '\b! .001', end='')
通过准备下一个屏幕写入来初始化消息,这将打印三个退格键作为 ⌫⌫⌫ rubout,然后是一个句点,擦除“001”并延长句点行。
在 search_string
模仿用户输入后,\b!
将我的 search_string
文本的感叹号修剪到后面 print()
强制使用的空格上,正确放置标点符号。接下来是一个空格和我正在模拟的“进度条”的第一个“点”。
不必要地,该消息还带有页码(格式为长度为 3 的前导零),以通知用户正在处理进度,这也将反映我们稍后将构建到的周期数正确的。
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.'+format(page, '03'))
行中。首先,要向左擦除,它将光标移到三个数字字符上,其中 '\b\b\b' 作为 ⌫⌫⌫ rubout 并删除一个新句点以添加到进度条长度。然后它会写出到目前为止它已经前进到的页面的三位数字。因为 sys.stdout.write()
等待一个完整的缓冲区或输出通道关闭,所以 sys.stdout.flush()
强制立即写入。 sys.stdout.flush()
内置在 print()
的末尾,被 print(txt, end='' )
绕过。然后代码循环执行其平凡的时间密集型操作,同时它不再打印任何内容,直到它返回此处擦除三个数字,添加一个句点并再次写入三个数字,递增。
擦除和重写的三个数字绝不是必要的 - 它只是一个体现 sys.stdout.write()
与 print()
的繁荣。您可以很容易地用句号作为底数,而忘记三个花哨的反斜杠-b ⌫ 退格(当然也不能写格式化的页数),只需每次打印句号栏长一长 - 没有空格或换行符,只使用sys.stdout.write('.'); sys.stdout.flush()
对。
请注意,Raspberry Pi IDLE 3 Python shell 不将退格视为 ⌫ rubout,而是打印一个空格,从而创建一个明显的分数列表。
只需使用 end
="" 或 sep
=""
>>> for i in range(10):
print('.', end = "")
输出:
.........
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)
或具有如下功能:
def Print(s):
return sys.stdout.write(str(s))
那么现在:
for i in range(10): # Or `xrange` for the Python 2 version
Print(i)
输出:
0123456789
只需使用 end=''
for i in range(5):
print('a',end='')
# aaaaa
for i in xrange(0,10): print '\b.',
这适用于 2.7.8 和2.5.2(分别为 Enthought Canopy 和 OS X 终端)——无需模块导入或时间旅行。
sys.stdout.isatty()
进行测试。
蟒蛇3:
print('Hello',end='')
例子 :
print('Hello',end=' ')
print('world')
输出:Hello world
此方法在提供的文本之间添加分隔符:
print('Hello','world',sep=',')
输出:Hello,world
您不需要导入任何库。只需使用删除字符:
BS = u'\0008' # The Unicode point for the "delete" character
for i in range(10):print(BS + "."),
这将删除换行符和空格 (^_^)*。
flush
以及它实际上做了什么吗?python -u my.py
取消缓冲所有 python 输出。如果您想实时查看进度,这通常是一个好主意。line = f"{line[6:]}?"
还有“结束”吗?