Skip to content Skip to sidebar Skip to footer

Reason For The Inability To Concatenate Strings And Ints In Python

It is well documented in numerous that str is required to convert ints to strings before they can be concatenated: 'I am ' + str(n) + ' years old.' There must be a fundamental rea

Solution 1:

you can use "," instead of "+" :

a=4
x=5
b=6
c=5
n=100
my_age="I am",n,"Years old"
print("I may say",my_age)

print('Consider the polynomial ' ,(a*x**2 + b*x + c))

Solution 2:

It has to do with the + operator.

When using the + operator, depending on the a and b variable types used in conjuncture with the operator, two functions may be called:

operator.concat(a, b) or operator.add(a, b)

The .concat(a, b) method returns a + b for sequences.

The .add(a, b) method returns a + b for numbers.

This can be found in the pydocs here.

Python doesn't implicitly convert variable types so that the function "works". That's too confusing for the code. So you must meet the requirements of the + operator in order to use it.

Post a Comment for "Reason For The Inability To Concatenate Strings And Ints In Python"