views:

343

answers:

9

How to print in python in one line.

Suppose I have iteration

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

It give me

1
2
3
4
......

but I want to be result like this

1 2 3 4 5 ...................

By the way...... How to refresh it every time so it print mi in one place just change the number.

+9  A: 

Use print item, to make the print statement omit the newline.

In Python 3, it's print(item, end=" ").

If you want every number to display in the same place, use for example (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),

In Python 3, it's a bit more complicated; here you need to flush sys.stdout or it won't print anything until after the loop has finished:

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()
Tim Pietzcker
Would be nice to make the second code sample work regardless of how many digits there are in the number.
Adam Crossland
Good idea :)...
Tim Pietzcker
Excellent. I added my own solution to the problem in my answer, but yours looks saner than mine.
Adam Crossland
Actually, it looks to me like your solution will print the same number of backspaces every time. So, if to is 20, it will print an extra backspace while printing digits 1..9. Shouldn't you calculate digits inside the loop and base it off of the value of i?
Adam Crossland
It right-justifies the number and always deletes everything. I haven't tested if it's faster to do that or to calculate in each iteration how many digits there are to be erased just now.
Tim Pietzcker
Or, base it off of the previous value of i to account for when the number of digits changes.
Adam Crossland
Ah, yes, i had over-looked the right-justification. Good solution.
Adam Crossland
Sounds fairly complicated. I probably wouldn't understand what I had done there if I had to look at my code a year from now. (Just had to read a program I wrote in 2007 - I'm *so* glad I wrote it in Python.)
Tim Pietzcker
I know it's more or less platform independent, but I can't say I like it. Having len( s ) and printing 2 * len( s ) characters... And what if there's newline somewhere? ( Yes, I'm shamelessly advertising my answer below ;) )
cji
+13  A: 

Change print item to:

print item,
ewall
+1  A: 
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.
Gary
that help question mark thing is an ipython nicety
Gary
+5  A: 

You can add a trailing comma to your print statement to print a space instead of a newline in each iteration:

print item,

Alternatively, if you're using Python 2.6 or later, you can use the new print function, which would allow you to specify that not even a space should come at the end of each item being printed (or allow you to specify whatever end you want):

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

Finally, you can write directly to standard output by importing it from the sys module, which returns a file-like object:

from sys import stdout
...
stdout.write( str(item) )
Eli Courtwright
+1  A: 
for i in xrange(1,100):
  print i,
eruciform
+1  A: 

To make the numbers overwrite each other, you can do something like this:

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

That should work as long as the number is printed in the first column.

EDIT: Here's a version that will work even if it isn't printed in the first column.

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

I should note that this code was tested and works just fine in Python 2.5 on Windows, in the WIndows console. According to some others, flushing of stdout may be required to see the results. YMMV.

Adam Crossland
Doesn't work - you need to flush stdout.
Zack
It works for me!
Adam Crossland
+2  A: 

By the way...... How to refresh it every time so it print mi in one place just change the number.

You have to use terminal control codes for this, like so:

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("\r  \r\n") # clean up

The stdout.flush is necessary, or you won't get any output. You could replace the stdout.write with a print statement but I prefer not to mix print with direct use of file objects.

Zack
What meen flush() function? Becouse it work for me without that function!
Pol
Normally, Python's file objects accumulate data so they can send it to the operating system in big chunks. This is what you want for access to files on disk, usually, but it interferes with this kind of task. `flush()` forces a file to send whatever it's got to the operating system right now. I'm surprised it works for you without that -- it didn't work for me until I added it.
Zack
I got win32 OS, and python 2.6. What kind of OS do you have?
Pol
Linux and python 2.6. It could very easily be a difference between Windows' "console windows" and Unix pseudoterminals. Don't worry about it for now.
Zack
A: 

"By the way...... How to refresh it every time so it print mi in one place just change the number."

It's really tricky topic. What zack suggested ( outputting console control codes ) is one way to achieve that.

You can use (n)curses, but that works mainly on *nixes.

On Windows (and here goes interesting part) which is rarely mentioned (I can't understand why) you can use Python bindings to WinAPI (http://sourceforge.net/projects/pywin32/ also with ActivePython by default) - it's not that hard and works well. Here's a small example:

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 )

Or, if you want to use print (statement or function, no difference):

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 module enables you to do many more interesting things with windows console... I'm not a big fan of WinAPI, but recently I realized that at least half of my antipathy towards it was caused by writing WinAPI code in C - pythonic bindings are much easier to use.

All other answers are great and pythonic, of course, but... What if I wanted to print on previous line? Or write multiline text, than clear it and write the same lines again? My solution makes that possible.

cji
A: 

If you just want to print the numbers, you can avoid the loop.

# 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 took 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 took 491.466823551ms

Mahmoud Kassem
Should be even faster with list comprehension instead of `map`.
cji
Yes good examples. I like it, but i need to show result of parsing.First I count the items i database than print how much remain.
Pol