views:

176

answers:

4

Hi, I want to create string in a for.

# Create string0, string1 ..... string10
for i in range [1,10]:
 string="string"+i

But I have returned an error because i is not a string but integer.

How I can do it?

Thanks.

+5  A: 
for i in range (1,10):
    string="string"+str(i)

To get string0, string1 ..... string10, you could do like

>>> ["string"+str(i) for i in range(11)]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9', 'string10']
S.Mark
Am I missing something to get a downvote?
S.Mark
Backticks are all sorts of silly.
Aaron Gallagher
It's still worth mentioning that backticks are equivalent to `repr()`, not `str()`.
Bastien Léonard
Bastien, Thanks for the note, but I think I don't put it back again.
S.Mark
3 Downvotes? Really!
S.Mark
Mmh, I tried to remove my vote (just a test), and then vote again; the vote is suppressed but I can't upvote it anymore... ("Your vote is now locked in unless this answer is edited")
Bastien Léonard
@Bastien, yeah, there is 5 minutes window to undo up/downvotes, but once its over, its stuck and can't do different vote until next edit. I think thats by-design
S.Mark
A: 
for i in range[1,10]: string = "string" + str(i)

str(i) castsconverts the integer into a string.

Rizwan Kassim
str(i) is conversion. Python doesn't have casting.
Aaron Gallagher
Thanks Aaron. Totally right.
Rizwan Kassim
+5  A: 
string = 'string%d' % (i,)
Ignacio Vazquez-Abrams
you only need to use a list for formatting when you have more than one format specifier, otherwise, it's ugly :)
Longpoke
That's not a list, that's a tuple. And you also need it if the single item to be formatted is itself a tuple.
Ignacio Vazquez-Abrams
+2  A: 
for i in range(11):
    string = "string{0}".format(i)

What you did (range[1,10]) is

  • a TypeError since brackets denote an index (a[3]) or a slice (a[3:5]) of a list,
  • a SyntaxError since [1,10] is invalid, and
  • a double off-by-one error since range(1,10) is [1, 2, 3, 4, 5, 6, 7, 8, 9], and you seem to want [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

And string = "string" + i is a TypeError since you can't add an integer to a string (unlike JavaScript).

Look at the documentation for Python's new string formatting method, it is very powerful.

Tim Pietzcker