Python String and Integer concatenation

michele picture michele · May 17, 2010 · Viewed 680.1k times · Source

I want to create string using integer appended to it, in a for loop. Like this:

for i in range(1,11):
  string="string"+i

But it returns an error:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

What's the best way to concatenate the String and Integer?

Answer

YOU picture YOU · May 17, 2010
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']