问题
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 reason why Python does not allow
'I am ' + n + ' years old.'
and I would like to learn what that reason is. In my project, I print a lot of numbers and end up with code like this.
'The GCD of the numbers ' + str(a) + ', ' + str(b) + ' and ' + str(c) + ' is ' + str(ans) + '.'
It would be much prettier if I could drop 'str'. And here's what makes my experience particularly vexing. I'm working with SymPy, so I have code like this:
'Consider the polynomial ' + (a*x**2 + b*x + c)
This works 99% percent of the time because we overloaded the '+' for SymPy expressions and strings. But we can't do it for ints and, as a result, this code fails when a=b=0 and the polynomial reduces to an integer constant! So for that outlier case, I'm forced to write:
'Consider the polynomial ' + str(a*x**2 + b*x + c)
So again, the solution 'string' + str(int) is straightforward, but the purpose of my post is to understand by Python doesn't allow 'string' + int the way, for instance, Java does.
回答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))
回答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.
来源:https://stackoverflow.com/questions/43956430/reason-for-the-inability-to-concatenate-strings-and-ints-in-python