Error in concatenating objects using Python

python

#1

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

>>> a='1'
>>> a+'2'
'12'
>>> len(a)
1
>>> 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.


#2

@Harshita_Dudhe

You can not add two non similar data types in Python

So you can add 1 & 2 to get 3

>>> 1 + 2
3

You can even add 2 strings

>>>'1'+'2'
'12'

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