5
votes

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.

6
SO each number will correspond to a letter like 1 = a, 2 = b? - Beginner
Kinda. If you write str(write your integer here) your integer will switch from the int data type to the str data type. I just assign that number that belongs to the str type to a variable named a or b or whatever you want to call it, as long as you follow the naming rules, so that I can use it later in my program - chilliefiber
@Beginner - no. a,b, etc are variables. (you can tell because they are not quoted and they're not numbers) So they stand for something. In this case, we assume from the title that they stand for integers. The str() function coerces a variable to present itself in a string representation - what that looks like depends on the variable type, but for integers, it's just the decimal representation, presented as a string. Notice that 1 != "1", as in most languages. (try evaluating "1" +"1") - Jon Kiparsky

6 Answers

19
votes

You can use map() to apply str() to each value in your array:

a = map(str, range(0, 10))

17
votes

Use a list comprehension:

[str(i) for i in range(10)]
5
votes

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']
0
votes

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 ...

0
votes

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.

0
votes
n = [0,1,2,3,4]
n = map(str,n)
n = list(n)
print(n)

Output:
n = ['0','1','2','3','4']