Error in concatenating objects using Python



Hello everyone,
I’m new at python. Can someone help me understand the following error:

>>> a='1'
>>> a+'2'
>>> len(a)
>>> a+len(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

When len(a) is 1, why am I not obtaining the value as ‘21’?

Thanks in advance.



You can not add two non similar data types in Python

So you can add 1 & 2 to get 3

>>> 1 + 2

You can even add 2 strings


But you can not add a string and a number. In the code you mention

a is a string and len(a) is a number. Hence the error. If you want 21, you can try something like this:

>>>str(len(a)+1) + a 

This should give you the desired result