动态打印一行

时间:2010-07-14 19:03:37

标签: python printing

我想做几个语句,提供标准输出,而不会在语句之间看到换行符。

具体来说,假设我有:

for item in range(1,100):
    print item

结果是:

1
2
3
4
.
.
.

如何让它看起来像:

1 2 3 4 5 ...

更好的是,是否可以在最后一个号码上打印单个号码 ,因此屏幕上一次只能显示一个号码?

22 个答案:

答案 0 :(得分:432)

print item更改为:

    Python 2.7中的
  • print item,
  • Python 3中的
  • print(item, end=" ")

如果要动态打印数据,请使用以下语法:

    Python 3中的
  • print(item, sep=' ', end='', flush=True)

答案 1 :(得分:141)

  

顺便说一句......如何每次刷新它以便在一个地方打印mi只需更改数字。

一般来说,这样做的方法是使用terminal control codes。这是一个特别简单的情况,你只需要一个特殊字符:U + 000D CARRIAGE RETURN,用Python(以及许多其他语言)编写'\r'。以下是基于您的代码的完整示例:

from sys import stdout
from time import sleep
for i in range(1,20):
    stdout.write("\r%d" % i)
    stdout.flush()
    sleep(1)
stdout.write("\n") # move the cursor to the next line

有些事情可能令人惊讶:

  • \r位于字符串的开头,这样,在程序运行时,光标将始终位于数字后面。这不仅仅是装饰性的:如果你反过来,一些终端模拟器会非常困惑。
  • 如果您不包含最后一行,那么在程序终止后,您的shell将在该数字的顶部打印其提示。
  • 某些系统上需要stdout.flush,否则您将无法获得任何输出。其他系统可能不需要它,但它不会造成任何伤害。

如果您发现这不起作用,您首先要怀疑的是您的终端模拟器是错误的。 vttest程序可以帮助您进行测试。

您可以使用stdout.write语句替换print,但我不希望将print与直接使用文件对象混合使用。

答案 2 :(得分:48)

使用print item,使print语句省略换行符。

在Python 3中,它是print(item, end=" ")

如果您希望每个数字都显示在同一个地方,请使用例如(Python 2.7):

to = 20
digits = len(str(to - 1))
delete = "\b" * (digits + 1)
for i in range(to):
    print "{0}{1:{2}}".format(delete, i, digits),

在Python 3中,它有点复杂;在这里你需要刷新sys.stdout,否则在循环完成之前它不会打印任何东西:

import sys
to = 20
digits = len(str(to - 1))
delete = "\b" * (digits)
for i in range(to):
   print("{0}{1:{2}}".format(delete, i, digits), end="")
   sys.stdout.flush()

答案 3 :(得分:16)

与其他例子一样,
我使用类似的方法,但不是花时间计算最后的输出长度等,

我只是使用ANSI代码转义返回到行的开头,然后在打印当前状态输出之前清除整行。

import sys

class Printer():
    """Print things to stdout on one line dynamically"""
    def __init__(self,data):
        sys.stdout.write("\r\x1b[K"+data.__str__())
        sys.stdout.flush()

要在迭代循环中使用,您只需调用类似:

x = 1
for f in fileList:
    ProcessFile(f)
    output = "File number %d completed." % x
    Printer(output)
    x += 1   

See more here

答案 4 :(得分:14)

您可以在print语句中添加一个尾随逗号,以便在每次迭代中打印空格而不是换行符:

print item,

或者,如果您使用的是Python 2.6或更高版本,则可以使用新的打印功能,这样您就可以指定在每个打印项目的末尾都不会有空格(或允许您指定无论你想要什么结果):

from __future__ import print_function
...
print(item, end="")

最后,您可以通过从sys模块导入标准输出直接写入标准输出,该模块返回类似文件的对象:

from sys import stdout
...
stdout.write( str(item) )

答案 5 :(得分:10)

变化

print item

print "\033[K", item, "\r",
sys.stdout.flush()
  • " \ 033 [K"清除到行尾
  • \ r \ n,返回行的开头
  • flush语句确保它立即显示,以便您获得实时输出。

答案 6 :(得分:5)

我认为简单的连接应该有效:

nl = []
for x in range(1,10):nl.append(str(x))
print ' '.join(nl)

答案 7 :(得分:4)

我在2.7上使用的另一个答案,我只打印了一个"。"每次循环运行(向用户表明事情仍然在运行)是这样的:

print "\b.",

打印"。"每个之间没有空格的字符。它看起来好一点,效果很好。对于那些想知道的人来说,\ b是一个退格符。

答案 8 :(得分:3)

“顺便说一句......如何每次刷新它以便在一个地方打印mi只需更改数字。”

这是一个非常棘手的话题。建议 zack (输出控制台控制代码)是实现这一目标的一种方法。

你可以使用(n)curses,但主要用于* nixes。

在Windows上(这里有趣的部分)很少提到(我无法理解为什么)你可以使用Python绑定到WinAPI(http://sourceforge.net/projects/pywin32/默认情况下也使用ActivePython) - 它并不那么难并且有效好。这是一个小例子:

import win32console, time

output_handle = win32console.GetStdHandle(  win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]

for i in "\\|/-\\|/-":
    output_handle.WriteConsoleOutputCharacter( i, pos )
    time.sleep( 1 )

或者,如果你想使用print(陈述或功能,没有区别):

import win32console, time

output_handle = win32console.GetStdHandle(  win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]

for i in "\\|/-\\|/-":
    print i
    output_handle.SetConsoleCursorPosition( pos )
    time.sleep( 1 )

win32console模块让你可以用Windows控制台做更多有趣的事情......我不是WinAPI的忠实粉丝,但最近我意识到我对它的反感至少有一半是由写作引起的C - pythonic绑定中的WinAPI代码更容易使用。

当然,所有其他答案都很棒而且是pythonic,但是......如果我想在之前的行打印怎么办?或者写多行文字,而不是清除它并再次写相同的行?我的解决方案使这成为可能。

答案 9 :(得分:3)

这么多复杂的答案。如果您使用的是python 3,只需在打印开始处放置\r,然后在其中添加end='', flush=True

import time

for i in range(10):
    print(f'\r{i} foo bar', end='', flush=True)
    time.sleep(0.5)

这将在原位写入0 foo bar,然后写入1 foo bar等。

答案 10 :(得分:2)

要使数字相互覆盖,您可以执行以下操作:

for i in range(1,100):
    print "\r",i,

只要在第一列中打印出数字,这就应该有效。

编辑: 这是一个即使没有在第一列中打印也能正常工作的版本。

prev_digits = -1
for i in range(0,1000):
    print("%s%d" % ("\b"*(prev_digits + 1), i)),
    prev_digits = len(str(i))

我应该注意这个代码已经过测试,在Windows上的Python 2.5中,在WIndows控制台中运行得很好。根据其他一些人的说法,可能需要冲洗标准品来查看结果。 YMMV。

答案 11 :(得分:2)

for Python 2.7

for x in range(0, 3):
    print x,

for Python 3

for x in range(0, 3):
    print(x, end=" ")

答案 12 :(得分:1)

for i in xrange(1,100):
  print i,

答案 13 :(得分:1)

In [9]: print?
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in function print>
Namespace:      Python builtin
Docstring:
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.

答案 14 :(得分:0)

或更简单:

import time
a = 0
while True:
    print (a, end="\r")
    a += 1
    time.sleep(0.1)

end="\r"将从第一张打印的开始[0:]开始覆盖。

答案 15 :(得分:0)

实现此目的的最佳方法是使用\r字符

试试以下代码:

import time
for n in range(500):
  print(n, end='\r')
  time.sleep(0.01)
print()  # start new line so most recently printed number stays

答案 16 :(得分:0)

for item in range(1,100):
    if item==99:
        print(item,end='')
    else:
        print (item,end=',')

输出: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25, 26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50, 51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75, 76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99

答案 17 :(得分:0)

对于那些像我一样挣扎的人,我想出了以下似乎在python 3.7.4和3.5.2中都起作用的东西。

我将范围从100扩展到1,000,000,因为它运行非常快,您可能看不到输出。这是因为设置end='\r'的一个副作用是最终循环迭代会清除所有输出。需要更长的数量才能证明其有效。 此结果可能并非在所有情况下都令人满意,但在我看来还不错,并且OP没有指定一种方法或另一种方法。您可以使用if语句规避此问题,该语句评估要迭代的数组的长度,依此类推。 在我的情况下,使其工作的关键是将括号"{}".format()耦合在一起。否则,它将无法正常工作。

以下应按原样工作:

#!/usr/bin/env python3

for item in range(1,1000000):
    print("{}".format(item), end='\r', flush=True)

答案 18 :(得分:0)

在Python 3中,您可以这样做:

for item in range(1,10):
    print(item, end =" ")

输出:

1 2 3 4 5 6 7 8 9 

元组:你可以用元组做同样的事情:

tup = (1,2,3,4,5)

for n in tup:
    print(n, end = " - ")

输出:

1 - 2 - 3 - 4 - 5 - 

另一个例子:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for item in list_of_tuples:
    print(item)

<强>输出:

(1, 2)
('A', 'B')
(3, 4)
('Cat', 'Dog')

你甚至可以像这样解压缩你的元组:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]

# Tuple unpacking so that you can deal with elements inside of the tuple individually
for (item1, item2) in list_of_tuples:
    print(item1, item2)   

<强>输出:

1 2
A B
3 4
Cat Dog

另一种变体:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for (item1, item2) in list_of_tuples:
    print(item1)
    print(item2)
    print('\n')

<强>输出:

1
2


A
B


3
4


Cat
Dog

答案 19 :(得分:0)

如果您只想打印数字,可以避免循环。

# python 3
import time

startnumber = 1
endnumber = 100

# solution A without a for loop
start_time = time.clock()
m = map(str, range(startnumber, endnumber + 1))
print(' '.join(m))
end_time = time.clock()
timetaken = (end_time - start_time) * 1000
print('took {0}ms\n'.format(timetaken))

# solution B: with a for loop
start_time = time.clock()
for i in range(startnumber, endnumber + 1):
    print(i, end=' ')
end_time = time.clock()
timetaken = (end_time - start_time) * 1000
print('\ntook {0}ms\n'.format(timetaken))

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 花了21.1986929975ms

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 花了491.466823551ms

答案 20 :(得分:-1)

适用于Python(2.7)

 l=""                             #empty string variable
    for item in range(1,100):
        item=str(item)            #converting each element to string
        l=l+" "+item              #concating each element
        l.lstrip()                # deleting the space that was created initially 
    print l                      #prining the whole string

Python 3

 l=""
        for item in range(1,100):
            item=str(item)
            l=l+" "+item
            l.lstrip()
        print(l)

答案 21 :(得分:-1)

如果你想要它作为一个字符串,你可以使用

number_string = ""
for i in range(1, 100):
  number_string += str(i)
print(number_string)
相关问题