Python String and Integer concatenation
Solution 1
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)]
Update as per Python3
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)]
Solution 2
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']
Solution 3
for i in range[1,10]:
string = "string" + str(i)
The str(i)
function converts the integer into a string.
Solution 4
string = 'string%d' % (i,)
Solution 5
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.
michele
Updated on July 08, 2022Comments
-
michele almost 2 years
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?