How to print a string one char at a time, with no spaces?

Michael Hudson mwh at python.net
Fri Oct 18 09:02:30 EDT 2002


Richard Bow <donkan7 at yahoo.com> writes:

> I'd like to write a script that appears to be calculating digits of pi and 
> spitting them out one at a time, with no spaces, such as below (pi to 1002 
> digits, gotten from http://www.angio.net/pi/piquery ). It's easy to do this 
> by 
> 
> pi = str(pi)
> for k in range(len(pi)):
>    print pi[k],
> 
> but this prints 3 . 1 4 1 5 9 2 6 5 ...
> 
> How to print without those Python spaces (which are very nice when you want 
> them)?

Two options:

1) don't use print at all, use sys.stdout.write() instead:

    >>> for c in str(math.pi):
    ...     sys.stdout.write(c)
    ... else:
    ...     sys.stdout.write('\n')
    ... 
    3.14159265359
    >>> 


2) reset sys.stdout.softspace after each print:

    >>> for c in str(math.pi):
    ...     print c,
    ...     sys.stdout.softspace = 0
    ... else:
    ...     print
    ... 
    3.14159265359
    >>> 

Cheers,
M.

-- 
  I have gathered a posie of other men's flowers, and nothing but
  the thread that binds them is my own.                   -- Montaigne



More information about the Python-list mailing list