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.
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.
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']
for i in range[1,10]: string = "string" + str(i)
str(i) castsconverts the integer into a string.
for i in range(11):
string = "string{0}".format(i)
What you did (range[1,10]
) is
a[3]
) or a slice (a[3:5]
) of a list, [1,10]
is invalid, and 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.