how to convert string

Fredrik Lundh fredrik at pythonware.com
Wed Apr 5 14:45:42 EDT 2006


diffuser78 at gmail.com wrote:

> I want to print number 0 to 9 in one line like this
> 0 1 2 3 4 5 6 7 8 9
>
> if I do like this, it prints in different lines
>
> for i in xrange(10):
>     print i
>
> so i tried like this
>
> str = ""
> for i in xrange(10):
>     str = i + " "
> print str
>
> but i want to know how convert int i to string.

the conversion function is called str(), so you might
want to rename that variable...

    out = ""
    for i in xrange(10):
        out = out + str(i) + " "
    print out

on the other hand, since print adds spaces between items printed
on the same line, you can simply do

    for i in range(10):
        print i,
    print

or you could use join, like

    print " ".join(str(i) for i in range(10))

or

    print " ".join(map(str, range(10)))

</F>






More information about the Python-list mailing list