Monday, 22 January 2024

TypeError: can only concatenate str (not "int") to str

You will get the error 'TypeError: can only concatenate str (not "int") to str', when you use the + operator to add an integer to a string because this is ungrammatical in Python. You can use + operator to add two numbers together or concatenate two strings, but not the combination.

>>> name = 'Krishna'
>>> age = 35
>>> msg = 'Hi, my name is ' + name + ' and I am ' + age + ' years old.'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

How to solve this problem?

To concatenate a string with an integer like 35, you must convert 35 into its string representation '35'. This can be achieved by using the str() function, which takes an integer as input and returns its string equivalent, as demonstrated below:

>>> msg = 'Hi, my name is ' + name + ' and I am ' + str(age) + ' years old.'
>>> msg
'Hi, my name is Krishna and I am 35 years old.'



Previous                                                 Next                                                 Home

No comments:

Post a Comment