在计算中包含字符串时Python中出现错误

时间:2019-01-17 21:11:23

标签: javascript python

我用Javascript进行了计算,无论我做什么,我都无法在Python中获得相同的结果。

这是有效的Javascript代码

================================================ ==================

firstNumber = 56
secondNumber = 22

addResult = firstNumber + secondNumber
subtractResult = firstNumber - secondNumber

console.log(firstNumber + ' + ' + secondNumber + ' = ' + addResult)
console.log(firstNumber + ' - ' + secondNumber + ' = ' + subtractResult)

================================================ ==================

它以这个结果结束...

================================================ ==================

56 + 22 = 78
56 - 22 = 34

================================================ ==================

这是我想要相同结果的Python代码

================================================ ==================

firstNumber = 56
secondNumber = 22

addResult = firstNumber + secondNumber
subtractResult = firstNumber - secondNumber

What next???

================================================ ==================

我尝试的一切都以错误结尾,有人对此有答案吗?

2 个答案:

答案 0 :(得分:-2)

接下来,您只需要执行一些python字符串连接即可。见下文!

print('{0} + {1} = {2}'.format(firstNumber, secondNumber, addResult))
print('{0} - {1} = {2}'.format(firstNumber, secondNumber, subtractResult))

答案 1 :(得分:-2)

如果要打印:

56 + 22 = 78
56 - 22 = 34

我会做(python 3.6):

firstNumber = 56
secondNumber = 22

print(f"{firstNumber} + {secondNumber} = {firstNumber + secondNumber}")
print(f"{firstNumber} - {secondNumber} = {firstNumber - secondNumber}")