Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I concatenate a string and a number in Python? [duplicate]

Tags:

python

I was trying to concatenate a string and a number in Python. It gave me an error when I tried this:

"abc" + 9 

The error is:

Traceback (most recent call last):   File "<pyshell#5>", line 1, in <module>     "abc" + 9 TypeError: cannot concatenate 'str' and 'int' objects 

Why I am not able to do this?

How can I concatenate a string and a number in Python?

like image 669
NOOB Avatar asked Aug 08 '11 11:08

NOOB


People also ask

How do you concatenate a string and a number 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.

How do I combine numbers and strings?

To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.

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

The answer to your question is "no". A number can have one of several C types (e.g. int , double , ...), but only one of them, and string is not a numeric type.


1 Answers

Python is strongly typed. There are no implicit type conversions.

You have to do one of these:

"asd%d" % 9 "asd" + str(9) 
like image 143
Jochen Ritzel Avatar answered Sep 27 '22 20:09

Jochen Ritzel