Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python String and Integer concatenation [duplicate]

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?

like image 936
michele Avatar asked May 17 '10 07:05

michele


People also ask

How do you concatenate an integer and a string in Python?

If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.

Can string and int concatenation in Python?

Python supports string concatenation using + operator. In most of the programming languages, if we concatenate a string with an integer or any other primitive data types, the language takes care of converting them to string and then concatenate it.

How do you print a string and int in the same line in Python?

Use comma “,” to separate strings and variables while printing int and string in the same line in Python or convert the int to string.

Can you use with a number and string in the same operation Python?

Since Python is a strongly typed language, concatenating a string and an integer, as you may do in Perl, makes no sense, because there's no defined way to "add" strings and numbers to each other.


2 Answers

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)] 
like image 90
Anirban Nag 'tintinmj' Avatar answered Sep 21 '22 05:09

Anirban Nag 'tintinmj'


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'] 
like image 38
YOU Avatar answered Sep 20 '22 05:09

YOU