383

I want to create a string using an 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?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
michele
  • 25,820
  • 29
  • 99
  • 158

9 Answers9

307

NOTE:

The method used in this answer (backticks) is deprecated in later versions of Python 2, and removed in Python 3. Use the str() function instead.


You can use:

string = 'string'
for i in range(11):
    string +=`i`
print string

It will print string012345678910.

To get string0, string1 ..... string10 you can use this as YOU suggested:

>>> string = "string"
>>> [string+`i` for i in range(11)]

For Python 3

You can use:

string = 'string'
for i in range(11):
    string += str(i)
print string

It will print string012345678910.

To get string0, string1 ..... string10, you can use this as YOU suggested:

>>> string = "string"
>>> [string+str(i) for i in range(11)]
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Anirban Nag 'tintinmj'
  • 5,392
  • 4
  • 35
  • 51
276
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']
YOU
  • 114,140
  • 31
  • 183
  • 213
  • Am I missing something to get a downvote? – YOU May 17 '10 at 08:52
  • 3
    It's still worth mentioning that backticks are equivalent to `repr()`, not `str()`. – Bastien Léonard May 17 '10 at 09:06
  • 1
    Bastien, Thanks for the note, but I think I don't put it back again. – YOU May 17 '10 at 09:28
  • 1
    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 May 17 '10 at 09:56
  • 1
    @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 – YOU May 17 '10 at 10:04
37
for i in range[1,10]: 
  string = "string" + str(i)

The str(i) function converts the integer into a string.

Eric Leschinski
  • 135,913
  • 89
  • 401
  • 325
Rizwan Kassim
  • 7,629
  • 3
  • 23
  • 34
36
string = 'string%d' % (i,)
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
22
for i in range(11):
    string = "string{0}".format(i)

You did (range[1,10]):

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

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Tim Pietzcker
  • 313,408
  • 56
  • 485
  • 544
4

You can use a generator to do this!

def sequence_generator(limit):
    """ A generator to create strings of pattern -> string1,string2..stringN """
    inc  = 0
    while inc < limit:
        yield 'string' + str(inc)
        inc += 1

# To generate a generator. Notice I have used () instead of []
a_generator  =  (s for s in sequence_generator(10))

# To generate a list
a_list  =  [s for s in sequence_generator(10)]

# To generate a string
a_string =  '['+ ", ".join(s for s in sequence_generator(10)) + ']'
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
1

If we want output like 'string0123456789' then we can use the map function and join method of string.

>>> 'string' + "".join(map(str, xrange(10)))
'string0123456789'

If we want a list of string values then use the list comprehension method.

>>> ['string'+i for i in map(str,xrange(10))]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9']

Note:

Use xrange() for Python 2.x.

Use range() for Python 3.x.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Vivek Sable
  • 9,246
  • 3
  • 34
  • 50
  • Perhaps link (non-naked) to documentation for all those functions? (But ***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today.) – Peter Mortensen Apr 03 '22 at 17:59
1

I did something else.

I wanted to replace a word, in lists of lists, that contained phrases.

I wanted to replace that string / word with a new word that will be a join between string and number, and that number / digit will indicate the position of the phrase / sublist / lists of lists.

That is, I replaced a string with a string and an incremental number that follow it.

myoldlist_1 = [[' myoldword'], [''], ['tttt myoldword'], ['jjjj ddmyoldwordd']]
    No_ofposition = []
    mynewlist_2 = []
    for i in xrange(0, 4, 1):
        mynewlist_2.append([x.replace('myoldword', "%s" % i + "_mynewword") for x in myoldlist_1[i]])
        if len(mynewlist_2[i]) > 0:
            No_ofposition.append(i)

mynewlist_2
No_ofposition
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
-6

Concatenation of a string and integer is simple: just use

abhishek+str(2)
Jemshit Iskenderov
  • 8,415
  • 5
  • 60
  • 98
Hiro
  • 2,774
  • 1
  • 14
  • 9
  • If it is so simple, perhaps explain (here or in the answer) why the previous seven answers weren't? E.g., did something change with later versions of Python? – Peter Mortensen Apr 03 '22 at 18:03