This question already has an answer here:
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?
The
str(i)
function converts the integer into a string.Concatenation of a string and integer is simple: just use
What you did (
range[1,10]
) isa[3]
) or a slice (a[3:5]
) of a list,[1,10]
is invalid, andrange(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.
You can use a generator to do this !
I did something else. I wanted to replace a word, in lists off lists, that contained phrases. I wanted to replace that sttring / 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.