首页 文章

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

提问于
浏览
1487

问题出在 Headers 中 .

我想在python做这件事 . 我想在_135151中的这个例子中做些什么:

#include <stdio.h>

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

输出:

..........

在Python中:

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

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

26 回答

  • 3

    或者具有如下功能:

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

    那么现在:

    for i in range(10): # or `xrange` for python 2 version
       Print(i)
    

    输出:

    0123456789
    
  • 3

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

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

    这适用于2.7.8和2.5.2(分别为Canopy和OSX终端) - 无需模块导入或时间旅行 .

  • 14

    新的(从Python 3.0开始) print 函数有一个可选的 end 参数,可以让你修改结束字符 . 分隔符也有 sep .

  • 8

    其中许多答案似乎有点复杂 . 在Python 3.X中你只需要这样做,

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

    end的默认值为“\ n” . 我们只是将其更改为空格,或者您也可以使用end =“” .

  • -1

    您会注意到以上所有答案都是正确的 . 但我想创建一个快捷方式,最后总是写出“end =''”参数 .

    你可以定义一个像这样的函数

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

    它会接受所有参数 . 即使它会接受所有其他参数,如文件,刷新等,并具有相同的名称 .

  • 0

    @lenooh满足了我的疑问 . 我在搜索'python suppress newline'时发现了这篇文章 . 我在Raspberry Pi上使用IDLE3为PuTTY开发Python 3.2 . 我想在PuTTY命令行上创建一个进度条 . 我不希望页面滚动 . 我想要一条水平线来重新确保用户不要害怕程序没有停止运转,也不会在快乐的无限循环中被送到午餐 - 作为请求'离开我,我做得很好,但这可能需要一些时间 . 交互式消息 - 就像文本中的进度条 .

    print('Skimming for', search_string, '\b! .001', end='') 通过准备下一个屏幕写入来初始化消息,这将打印三个退格区域作为⌫⌫⌫rubout然后一个句点,擦除'001'并延长周期线 . 在 search_string 鹦鹉用户输入之后, \b! 修剪我的 search_string 文本的感叹号,以覆盖 print() 否则强制的空格,正确放置标点符号 . 那个's followed by a space and the first '点' of the '进度条' which I'米模拟 . 不必要的是,该消息也随后用页码编号(格式化为带有前导零的三个长度)以从用户处注意到正在处理进度并且还将反映我们稍后将构建到的时段的计数 . 对 .

    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'作为⌫⌫⌫擦除,并删除一个新的句点以添加到进度条长度 . 然后它写了它已经进展到的页面的三个数字到目前为止 . 因为 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 IDLE3 Python shell不支持退格为⌫rubout,而是打印一个空格,而是创建一个明显的分数列表 .

    • (o = 8> wiz
  • 1

    你想在for循环中打印一些东西;但是你不希望它每次都在新行中打印..例如:

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

    但你希望它像这样打印:嗨嗨嗨嗨嗨右????只需在打印后添加逗号“hi”

    例:

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

  • 15

    你可以试试:

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

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

    Re:没有c / 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
    >>>
    
  • 2043

    这是一种不插入换行符的一般打印方式 .

    Python 3

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

    在Python 3中,它实现起来非常简单

  • 14

    python 2.6+

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

    python 3

    print('.', end='')
    

    python <= 2.5

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

    如果在每次打印后额外的空间都可以,则在python 2中

    print '.',
    

    misleading 在python 2中 - avoid

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

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

    若要不破坏所有python2打印关键字,请创建单独的 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
    
  • 4
    for i in xrange(0,10): print '.',
    

    这对你有用 . 这里逗号(,)在打印后很重要 . 得到了帮助:http://freecodeszone.blogspot.in/2016/11/how-to-print-in-python-without-newline.html

  • 11

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

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

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

  • 37

    Code for Python 3.6.1

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

    Output

    ..........
    >>>
    
  • 23

    python中的 print 函数自动生成一个新行 . 你可以尝试:

    print("Hello World", end="")

  • 4

    一般方式

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

    您可能还需要打电话

    sys.stdout.flush()
    

    确保立即刷新 stdout .

    Python 2.6

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

    from __future__ import print_function
    

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

    Python 3

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

    print('.', end='')
    

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

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

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

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

    来源

  • 87

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

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

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

    print ('hello world')
    

    Python将其翻译为

    print ('hello world', end = '\n')
    

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

    print ('hello world', end = '')
    print ('hello world', end = ' ')
    
  • 7

    您可以使用 printend 参数执行此操作 . 在Python3中, range() 返回迭代器, xrange() 不存在 .

    for i in range(10): print('.', end='')
    
  • 4

    注意:这个问题的 Headers 曾经像"How to printf in python?"

    由于人们可能会根据 Headers 来到这里寻找它,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
    ..........
    
  • 4

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

    我解决了这个问题:

    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)
    

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

    心连心

  • 6

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

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

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

  • 4

    您可以在python3中执行相同操作,如下所示:

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

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

  • 0

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

    Print without newline in Python 3.x

    在print语句后不附加任何内容,并使用 end='' 删除'\n':

    >>> print('hello')
    hello  # appending '\n' automatically
    >>> print('world')
    world # with previous '\n' world comes down
    
    # solution is:
    >>> print('hello', end='');print(' world'); # end with anything like end='-' or end=" " but not '\n'
    hello world # it seem correct output
    

    Another Example in Loop

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

    Print without newline in Python 2.x

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

    >>> print "hello",; print" world"
    hello world
    

    Another Example in Loop

    for i in range(1,10):
        print "{} .".format(i),
    

    希望这会帮助你 . 你可以访问这个link .

相关问题