【问题标题】:How to print without a newline or space如何在没有换行符或空格的情况下打印
【发布时间】:2010-10-04 08:24:36
【问题描述】:

我想用 Python 来做。我想在 C 中的这个例子中做什么:

#include <stdio.h>

int main() {
    int i;
    for (i=0; i<10; i++) printf(".");
    return 0;
}

输出:

..........

在 Python 中:

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

在 Python 中,print 将添加一个 \n 或空格。我怎样才能避免这种情况?我想知道如何将字符串“附加”到stdout

【问题讨论】:

标签: python


【解决方案1】:

在 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 3.6.3 中,flush=True 至关重要,否则它不会按预期工作。
  • 谁能解释我为什么需要flush 以及它实际上是做什么的?
  • 晚了几个月,但回答@Rishav flush 清空缓冲区并立即显示输出。如果没有刷新,您最终可能会打印出确切的文本,但只有当系统开始处理图形而不是 IO 时。 Flush 通过“刷新”缓存使文本立即可见。
  • 如果您在缓冲时遇到问题,您可以使用 python -u my.py 取消缓冲所有 python 输出。如果您想实时查看进度,这通常是个好主意。
  • 我用的是格式字符串,不想在字符串和之间换行?:line = f"{line[6:]}?"还有“end”吗?
【解决方案2】:

对于 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
>>>

【讨论】:

  • 由于空格,这在问题中被特别列为不良行为
  • 相反,应该删除答案有两个原因:它具有您无法禁用的不良副作用(包括额外的空格),并且它与 python 3 不兼容(括号强制转换为元组)。我期望这些来自 PHP 的劣质构造,而不是 Python。所以最好不要使用它。
  • // ,不过,这是在 Python 2 中完成它的最简单方法,并且对于真正旧的操作系统有很多一次性代码。可能不是最好的解决方案,甚至不推荐。然而,StackOverflow 的一大优势是它让我们知道那里有什么奇怪的技巧。 KDP,您能否在顶部添加一个关于@Eric Leschinski 所说内容的快速警告?毕竟,这确实是有道理的。
  • @nathanbasanese 简单与否,它有一个副作用,提问者明确不想要。投反对票。
  • 如何在每个 N 之后摆脱那个空间,即我想要 0123456..
【解决方案3】:

注意:这个问题的标题曾经是“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
..........

【讨论】:

  • 确实,它没有抓住重点。 :) 因为这个问题已经有了很好的答案,所以我只是在详细阐述一些可能有用的相关技术。
  • 基于问题的标题,我相信这个答案更适合类比在 C/C++ 中通常使用 printf 的方式
  • 这回答了问题的标题,而不是正文。也就是说,它为我提供了我正在寻找的东西。 :)
  • 这不是问题的答案
  • @Vanuan,我在答案的底部解释说问题的标题在某些时候发生了变化。 :)
【解决方案4】:

对 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

【讨论】:

    【解决方案5】:

    如何在同一行打印:

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

    【讨论】:

      【解决方案6】:

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

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

      输出:

      你好

      还有sep作为分隔符:

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

      输出:

      喂喂喂喂

      如果您想在 Python 2.x 中使用它,只需在文件的开始处添加:

      from __future__ import print_function
      

      【讨论】:

      • “sep”是做什么的?
      • @McPeppr 我知道这很旧,但为了更清楚起见,我还是编辑了答案。立即检查。
      • 感谢您的编辑。 sep 会派上用场。到目前为止,我使用 sep.join(list) 将列表的元素与中间的分隔符连接起来 - 非常适合编写 csv 文件
      【解决方案7】:

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

      >>> import functools
      
      >>> printf = functools.partial(print, end="")
      
      >>> printf("Hello world\n")
      Hello world
      

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

      【讨论】:

      • 我曾经想这样做但不能这样做,因为otherfunction = function(1) 只会存储function(1) 的结果,而不是将otherfunction 放入包装器中。谢谢!
      【解决方案8】:

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

      print('Hello, World!')
      

      Python 将其翻译成

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

      您可以将end 更改为您想要的任何内容。

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

      【讨论】:

        【解决方案9】:

        在 Python 2.x 中,您只需在 print 函数的末尾添加 ,,这样它就不会在新行上打印。

        【讨论】:

        • // ,这实际上使它什么也没打印出来。难道我们不需要在最后添加另一个没有参数的打印语句,如stackoverflow.com/a/493500/2146138所示?你愿意用一个非常短的两行或三行示例来编辑这个答案吗?
        • OP 不希望添加空格
        • 没有回答问题。没有空格。
        • 这在 Python 2.x 中不再有效,只能回答 OP 想要的一半。为什么要 16 票?
        • @TheTechRobo36414519:有 25 个赞成票和 9 个反对票(总共 16 个)。从那时起,它得到了一张赞成票和一张反对票(所以现在总数仍然是 16)。
        【解决方案10】:

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

        在 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')
        • 您的 2.7 解决方案不会删除空格。
        • 我提到删除'\n'不是空格,空格在python2中是默认的。看看这是什么样子:print 'hello' ;print'there' in paiza.io/projects/e/35So9iUPfMdIORGzJTb2NQ
        • 对,这就是您的答案被否决的原因。您没有回答“如何在没有换行符或空格的情况下打印?”的问题。您对 2.x 的回答没有回答这个问题。您对 3.0 的回答与九年前发布的许多其他答案相同。简单地说,这个答案对社区没有任何用处,你应该删除它。
        【解决方案11】:

        Python 3

        print('.', end='')
        

        Python 2.6+

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

        Python

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

        【讨论】:

          【解决方案12】:

          你可以试试:

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

          【讨论】:

            【解决方案13】:

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

            我通过这样做解决了它:

            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__
            【解决方案14】:

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

            #!usr/bin/python
            
            i = 0
            while i<10 :
                print('.', end='')
                i = i+1
            

            并使用python filename.pypython3 filename.py 执行它。

            【讨论】:

              【解决方案15】:

              其中许多答案似乎有点复杂。在 Python 3.x 中,您只需这样做:

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

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

              【讨论】:

                【解决方案16】:

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

                【讨论】:

                • 不,OP想要hihihihihi,而不是hi hi hi hi hi
                【解决方案17】:

                您会注意到以上所有答案都是正确的。但我想创建一个捷径,总是在最后写入“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。现在它可以按我的意愿工作。所以一个人赞成这个想法。
                【解决方案18】:

                lenooh satisfied 我的查询。我在搜索“python suppress newline”时发现了这篇文章。我在 Raspberry Pi 上使用 IDLE 3PuTTY 开发 Python 3.2。

                我想在 PuTTY 命令行上创建一个进度条。我不希望页面滚动。我想要一条水平线来让用户放心,让用户不会因为程序没有停止运行,也没有在快乐的无限循环中被送去吃午饭而感到害怕——作为请求‘别管我,我做得很好,但是这个可能需要一些时间。交互式消息 - 就像文本中的进度条。

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

                search_string parrots 用户输入之后,\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,而是打印一个空格,从而创建一个明显的分数列表。

                【讨论】:

                  【解决方案19】:
                   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)
                  

                  【讨论】:

                    【解决方案20】:

                    或者有这样的功能:

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

                    那么现在:

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

                    输出:

                    0123456789
                    

                    【讨论】:

                      【解决方案21】:
                      for i in xrange(0,10): print '\b.',
                      

                      这适用于 2.7.8 和 2.5.2(分别为Enthought Canopy 和 OS X 终端)——无需模块导入或时间旅行。

                      【讨论】:

                      • 将退格字符打印到标准输出。如果标准输出恰好是一个终端,它可能看起来正确,但如果它被重定向到一个文件,该文件将包含控制字符。
                      • 没错,但我无法想象除了低科技的进度条之外会有人想用它来做任何事情......
                      • 不过,Python 代码的作用与问题中的 C 代码不同。
                      • 如果没有重定向到文件,您可以使用sys.stdout.isatty() 进行测试。
                      【解决方案22】:

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

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

                      输出:

                      .........
                      

                      【讨论】:

                      【解决方案23】:

                      Python3:

                      print('Hello',end='')
                      

                      例子:

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

                      输出: Hello world

                      此方法在提供的文本之间添加分隔符:

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

                      输出:Hello,world

                      【讨论】:

                        【解决方案24】:

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

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

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

                        【讨论】:

                          猜你喜欢
                          • 2012-04-16
                          • 1970-01-01
                          相关资源
                          最近更新 更多