how to convert string
Gary Herron
gherron at islandtraining.com
Wed Apr 5 14:59:27 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
>
>
A comma at the end of the print will do what you want:
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.
>
>
str(i) will do what you want and so will the "%" operator. However, you
sample code masks the builtin "str" function by creating a variable with
the same name (plus you had another error in that line), so try this:
s = ""
for i in xrange(10):
s = s + str(i) + " "
print s
A shortcut for the line in the loop is
s += str(i) + " "
Also note that appending to string is slow while appending to lists is not. So try build a list and turning it into a string with the string "join" method like this
l = []
for i in xrange(10):
l.append(str(i)
print " ".join(l)
Finally, you can build the list with a list comprehension construct
l = [str(i) for i in xrange(10)]
print " ".join(l)
You could also combine the above two lines into one -- that would be shorter, but probably not clearer.
Cheers,
Gary Herron
>Every help is appreciate.
>
>
>
More information about the Python-list
mailing list