如何在没有换行或空格的情况下打印?

And*_*mbu 1760 python newline python-2.x

问题出在标题中.

我想在做到这一点 .我想在中的这个例子中做些什么:

#include <stdio.h>

int main() {
    int i;
    for (i=0; i<10; i++) printf(".");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

..........
Run Code Online (Sandbox Code Playgroud)

在Python中:

>>> for i in xrange(0,10): print '.'
.
.
.
.
.
.
.
.
.
.
>>> for i in xrange(0,10): print '.',
. . . . . . . . . .
Run Code Online (Sandbox Code Playgroud)

在Python中print会添加一个\n或一个空格,我该如何避免呢?现在,这只是一个例子.不要告诉我,我可以先构建一个字符串然后打印它.我想知道如何"附加"字符串stdout.

cod*_*gic 2387

一般方式

import sys
sys.stdout.write('.')
Run Code Online (Sandbox Code Playgroud)

您可能还需要打电话

sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)

确保stdout立即冲洗.

Python 2.6+

从Python 2.6,您可以print从Python 3 导入该函数:

from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)

这允许您使用下面的Python 3解决方案.

Python 3

在Python 3中,print语句已更改为函数.在Python 3中,您可以改为:

print('.', end='')
Run Code Online (Sandbox Code Playgroud)

这也适用于Python 2,前提是您已经使用过from __future__ import print_function.

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

print('.', end='', flush=True)
Run Code Online (Sandbox Code Playgroud)

但请注意,在Python 2中导入flushprint函数版本中没有该关键字__future__; 它只适用于Python 3,更具体地说是3.3及更高版本.在早期版本中,您仍然需要通过调用手动刷新sys.stdout.flush().

来源

  1. https://docs.python.org/2/library/functions.html#print
  2. https://docs.python.org/2/library/__future__.html
  3. https://docs.python.org/3/library/functions.html#print

  • 谢谢!在 Python 3.6.3 中,flush=True 至关重要,否则它将无法按预期工作。 (7认同)
  • 如果您在缓冲方面遇到问题,可以使用“python -u my.py”取消缓冲所有 python 输出。如果您想实时观察进度,这通常是一个好主意。 (4认同)
  • 有人可以解释为什么我需要“冲洗”吗,它实际上有什么作用? (2认同)
  • 已经晚了几个月,但是要回答@Rishav flush,清空缓冲区并立即显示输出。如果没有刷新,则最终可能会打印出准确的文本,但是只有在系统开始处理图形而不是IO时才可以打印。刷新通过“刷新”缓存使文本立即可见。 (2认同)

小智 294

它应该像Guido Van Rossum在这个链接中所描述的那样简单:

Re:如何在没有ac/r的情况下打印?

http://legacy.python.org/search/hypermail/python-1992/0115.html

是否可以打印一些东西但不会自动附加回车符?

是的,在打印的最后一个参数后附加一个逗号.例如,此循环在由空格分隔的行上打印数字0..9.注意添加最终换行符的无参数"print":

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

  • 由于空格,这在问题中被特别列为不良行为 (95认同)
  • 相反,应删除答案有两个原因:它具有不能禁用的不良副作用(包括额外的空格),并且它与python 3不兼容(括号强制转换为元组) .我希望这些来自PHP的伪劣结构,而不是Python.所以最好不要使用它. (80认同)
  • @nathanbasanese简单与否,它有副作用*提问者明确不要*.Downvoted. (22认同)
  • //,这是在Python 2中完成它的最简单方法,并且有很多一次性代码用于真正的旧操作系统.可能不是最好的解决方案,甚至是推荐的解决方案.然而,StackOverflow的一大优势在于它让我们知道了什么怪异的技巧.KDP,你会在顶部快速警告@Eric Leschinski所说的内容吗?毕竟,它确实有意义. (9认同)
  • 270赞成答案_specifically_不回答问题.良好的工作支持人们.干得好. (8认同)
  • 如何在每个N之后摆脱那个空间,即我想要"0123456 ..." (5认同)
  • 您没有回答问题。“如何不使用换行符或***进行打印?” 他特别说没有空格。 (2认同)
  • @Cylindric:通常人们会通过Google找到与*他们*想要的东西不完全匹配的问题,但答案仍然对他们有用。大概在这291次投票中,大多数来自那些尾随空间不错的人,这与问题的要求不同。这就是SO的工作方式,尤其是针对许多情况下出现的FAQ。它并不能“合理化”这个答案,也不意味着任何一个都是好事,它只是说明了我们如何到达这里,并告诉我们这个答案实际上对很多人有帮助(至少看起来不错)。 (2认同)
  • 答案已经过时并且对于 Python3 来说是不正确的。Dowvnote 因为作者没有更新这个答案来表明它是针对遗留代码的。答案是对所发布问题的不完整解决方案。 (2认同)

Bea*_*eau 164

注意:这个问题的标题曾经是"如何在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
Run Code Online (Sandbox Code Playgroud)

并且,您可以轻松地乘以字符串值:

>>> print "." * 10
..........
Run Code Online (Sandbox Code Playgroud)

  • 这回答了问题的标题,但没有回答正文.那就是说,它为我提供了我想要的东西.:) (15认同)
  • 实际上,它缺少重点.:)由于这个问题已经有了很好的答案,我只是详细阐述了一些可能有用的相关技术. (9认同)
  • 基于问题的标题,我认为这个答案更适合于在C/C++中如何通常使用printf (7认同)
  • @Vanuan,我在答案的底部解释说,问题的标题在某些时候发生了变化.:) (4认同)
  • 这不是问题的答案 (2认同)
  • 这个答案不再重要了。 (2认同)

k10*_*107 91

对python2.6 +使用python3样式的打印函数 (也会破坏同一文件中任何现有的keyworded打印语句.)

# for python2 to use the print() function, removing the print keyword
from __future__ import print_function
for x in xrange(10):
    print('.', end='')
Run Code Online (Sandbox Code Playgroud)

若要不破坏所有python2打印关键字,请创建单独的printf.py文件

# printf.py

from __future__ import print_function

def printf(str, *args):
    print(str % args, end='')
Run Code Online (Sandbox Code Playgroud)

然后,在您的文件中使用它

from printf import printf
for x in xrange(10):
    printf('.')
print 'done'
#..........done
Run Code Online (Sandbox Code Playgroud)

更多示例显示printf样式

printf('hello %s', 'world')
printf('%i %f', 10, 3.14)
#hello world10 3.140000
Run Code Online (Sandbox Code Playgroud)


len*_*ooh 39

这不是标题中问题的答案,但它是关于如何在同一行上打印的答案:

import sys
for i in xrange(0,10):
   sys.stdout.write(".")
   sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)

  • 每次写入时flush()ing stdout都可能影响性能 (9认同)

Sil*_*ost 27

新的(从Python 3.0开始)print函数有一个可选end参数,允许您修改结束字符.还有sep分隔符.

  • “sep”有什么作用? (2认同)
  • @McPeppr我知道这已经很旧了,但为了更清楚我还是编辑了答案。现在检查。 (2认同)

小智 20

使用functools.partial创建一个名为printf的新函数

>>> import functools

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

>>> printf("Hello world\n")
Hello world
Run Code Online (Sandbox Code Playgroud)

使用默认参数包装函数的简便方法.


use*_*437 16

您可以添加功能,的末尾,print以便它不会在新行上打印.

  • 没有回答问题。没空间了。 (3认同)
  • // , 这实际上使它什么都不打印。难道我们不需要在末尾添加另一个没有参数的打印语句,如 http://stackoverflow.com/a/493500/2146138 所示?您愿意用一个非常短的两行或三行示例来编辑这个答案吗? (2认同)
  • OP不想添加空格 (2认同)
  • 这在 Python 2.x 中不再有效,并且只回答了 OP 想要的一半。为什么有 16 票赞成? (2认同)

小智 11

在Python 3中,打印是一种功能.你打电话的时候

print('hello world')
Run Code Online (Sandbox Code Playgroud)

Python将其翻译为

print('hello world', end='\n')
Run Code Online (Sandbox Code Playgroud)

您可以将结束更改为您想要的任何内容.

print('hello world', end='')
print('hello world', end=' ')
Run Code Online (Sandbox Code Playgroud)


sus*_*097 10

一般来说,有两种方法可以做到这一点:

Python 3.x 中不带换行符的打印

在 print 语句后不添加任何内容,并使用 , 删除 '\n' end='',如下所示:

>>> 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
Run Code Online (Sandbox Code Playgroud)

循环中的另一个例子

for i in range(1,10):
    print(i, end='.')
Run Code Online (Sandbox Code Playgroud)

Python 2.x 中不带换行符的打印

添加尾随逗号表示:打印后,忽略\n

>>> print "hello",; print" world"
hello world
Run Code Online (Sandbox Code Playgroud)

循环中的另一个例子

for i in range(1,10):
    print "{} .".format(i),
Run Code Online (Sandbox Code Playgroud)

您可以访问此链接


小智 9

只需使用end=''

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

# aaaaa
Run Code Online (Sandbox Code Playgroud)


alv*_*vas 8

你可以试试:

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')
Run Code Online (Sandbox Code Playgroud)


Lun*_*D10 8

只需使用end="" 或sep=""

>>> for i in range(10):
        print('.', end = "")
Run Code Online (Sandbox Code Playgroud)

输出:

.........
Run Code Online (Sandbox Code Playgroud)


n61*_*007 7

python 2.6+

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

的Python 3

print('.', end='')
Run Code Online (Sandbox Code Playgroud)

python <= 2.5

import sys
sys.stdout.write('.')
Run Code Online (Sandbox Code Playgroud)

如果每次打印后多余的空间都可以,在python 2中

print '.',
Run Code Online (Sandbox Code Playgroud)

在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') `
Run Code Online (Sandbox Code Playgroud)


小智 6

我最近遇到了同样的问题..

我解决了这个问题:

import sys, os

# reopen stdout 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)
Run Code Online (Sandbox Code Playgroud)

这适用于unix和windows ......还没有在macosx上测试过...

心连心

  • 中断`sys.__stdout__` (2认同)

Sub*_*bbu 5

您可以在python3中执行以下操作:

#!usr/bin/python

i = 0
while i<10 :
    print('.',end='')
    i = i+1
Run Code Online (Sandbox Code Playgroud)

并用python filename.py或执行python3 filename.py


小智 5

lenooh满足了我的询问。我在搜索“python抑制换行符”时发现了这篇文章。我正在 Raspberry Pi 上使用IDLE\xc2\xa03PuTTY开发 Python 3.2 。

\n

我想在 PuTTY 命令行上创建一个进度条。我不希望页面滚走。我想要一条水平线来安抚用户,以免他们惊慌失措,因为程序没有停止运行,也没有在快乐的无限循环中被发送去吃午饭——以此恳求“别打扰我,我做得很好” ,但这可能需要一些时间。\' 交互式消息 - 就像文本中的进度条。

\n

通过准备下一个屏幕写入来初始化print(\'Skimming for\', search_string, \'\\b! .001\', end=\'\')消息,这将打印三个退格键 \xe2\x8c\xab\xe2\x8c\xab\xe2\x8c\xab 擦除,然后打印一个句点,擦除 \'001\'并延长周期线。

\n

search_string鹦鹉学舌用户输入后,\\b!修剪我的文本的感叹号search_string以返回到空格print(),否则会强制正确放置标点符号。接下来是一个空格和我正在模拟的“进度条”的第一个“点”。

\n

不必要的是,该消息还带有页码(格式为长度为 3、前导零),以便用户注意到正在处理的进度,并且这也将反映我们稍后将构建到的周期计数。正确的。

\n
import sys\n\npage=1\nsearch_string=input(\'Search for?\',)\nprint(\'Skimming for\', search_string, \'\\b! .001\', end=\'\')\nsys.stdout.flush() # the print function with an end=\'\' won\'t print unless forced\nwhile page:\n    # some stuff\xe2\x80\xa6\n    # search, scrub, and build bulk output list[], count items,\n    # set done flag True\n    page=page+1 #done flag set in \'some_stuff\'\n    sys.stdout.write(\'\\b\\b\\b.\'+format(page, \'03\')) #<-- here\'s the progress bar meat\n    sys.stdout.flush()\n    if done: #( flag alternative to break, exit or quit)\n        print(\'\\nSorting\', item_count, \'items\')\n        page=0 # exits the \'while page\' loop\nlist.sort()\nfor item_count in range(0, items)\n    print(list[item_count])\n\n#print footers here\nif not (len(list)==items):\n    print(\'#error_handler\')\n
Run Code Online (Sandbox Code Playgroud)\n

进度条肉在排队sys.stdout.write(\'\\b\\b\\b.\'+format(page, \'03\'))。首先,要向左擦除,它将光标备份到三个数字字符上,其中 \'\\b\\b\\b\' 为 \xe2\x8c\xab\xe2\x8c\xab\xe2\x8c \xab 删除并删除一个新句点以添加进度条长度。然后它会写入目前为止已前进到的页面的三位数字。因为sys.stdout.write()等待缓冲区已满或输出通道关闭,所以sys.stdout.flush()强制立即写入。sys.stdout.flush()内置于其末端print(),并用 绕过print(txt, end=\'\' )。然后,代码循环执行日常的时间密集型操作,同时不再打印任何内容,直到返回此处擦除三位数字,添加句点并再次写入三位数字(递增)。

\n

擦除和重写的三位数字根本没有必要——这只是一个华丽的例子,说明了sys.stdout.write()与 的关系print()。您可以轻松地用句号打底,然后忘记三个奇特的反斜杠-b \xe2\x8c\xab 退格键(当然也不要写入格式化的页数),只需每次将句号栏加长一号即可 - 不带空格或仅使用该sys.stdout.write(\'.\'); sys.stdout.flush()对的换行符。

\n

请注意,Raspberry Pi IDLE 3 Python shell 不将退格键视为 \xe2\x8c\xab rubout,而是打印一个空格,从而创建一个明显的分数列表。

\n


小智 5

你想在for循环中正确打印一些东西;但你不希望它每次都以新行打印......

例如:

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

 OUTPUT:
    hi
    hi
    hi
    hi
    hi
Run Code Online (Sandbox Code Playgroud)

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

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

例子:

for i in range (0,5):
    print "hi",
Run Code Online (Sandbox Code Playgroud)

输出:

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

 OUTPUT:
    hi
    hi
    hi
    hi
    hi
Run Code Online (Sandbox Code Playgroud)

  • 不,OP 想要 hihihihihi,而不是 hi hi hi hi hi (6认同)

小智 5

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

print(<expr>, <expr>, ..., <expr>, end=" ")
Run Code Online (Sandbox Code Playgroud)

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


小智 5

您会注意到上述所有答案都是正确的。但是我想做一个捷径,总是总是在最后写入“ end =”参数。

你可以定义一个像

def Print(*args,sep='',end='',file=None,flush=False):
    print(*args,sep=sep,end=end,file=file,flush=flush)
Run Code Online (Sandbox Code Playgroud)

它将接受所有数量的参数。即使它将接受所有其他参数,如file,flush等,并且使用相同的名称。