0 votes
1 view
in Python by (42.5k points)

I want to create a string using integer appended to it, in a for a 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?

1 Answer

0 votes
by (95.7k points)

For creating a string using integer appended to it, in a for loop we have a method which is str().

You can use the below-mentioned code:-

string = 'string' for i in range(11): 

string +=`i` 

print(string)

image

If you want to get string0, string1 ..... string10 you can use the following code:-

string = "string" 

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

image

If you are a Python 3 user then you can use the following code:-

string = 'string' for i in range(11):

string +=str(i)

print(string)

image

And for getting string0, string1 ..... string10 you can use the below-mentioned code:-

string = "string" 

[string+str(i) for i in range(11)]

image

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...