Reputation: 651
I want to convert the integers from 0 to 9 to strings. I was able to do it by manually transforming each number like this:
str(1) = a
str(2) = b
... All the way untill 9. However, this is slow and the code doesn't look very pythonic. I would like to see a faster to code solution, such as putting all these numbers into a list and then transforming each element inside the list to a string. I know that to make said list I should do it like this:
a = range(0,10)
However, I don't know how to transform the ints inside the list to strings. Thanks in advance for your help.
Upvotes: 13
Views: 49538
Reputation: 12672
You can use map()
to apply str()
to each value in your array:
a = map(str, range(0, 10))
Upvotes: 27
Reputation: 7
n = [0,1,2,3,4]
n = map(str,n)
n = list(n)
print(n)
Output:
n = ['0','1','2','3','4']
Upvotes: 0
Reputation: 1948
If you need to convert the list of ints to a string of strings, you can do this:
a = range(0,10)
print "'" + "','".join((map(str,a))) + "'"
'0','1','2','3','4','5','6','7','8','9'
print type("'" + "','".join((map(str,a))) + "'")
<type 'str'>
This can be useful if you have many integer types that need to be queried as string types in a separate database, for example.
Upvotes: 0
Reputation: 451
Here is another answer:
a = map(chr, range(48, 58))
print a
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
Here is the docstring for chr which explains what I did:
Docstring:
chr(i) -> character
Return a string of one character with ordinal i; 0 <= i < 256
If you simply called chr(48) you will get '0' , chr(49)='1' and so on ...
Upvotes: 0
Reputation: 180411
You can use map
a = range(0,10)
print(list(map(str,a))) # <- python 3
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
a = xrange(0,10)
print(map(str,a)) # <- python 2
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
Upvotes: 6