【问题标题】:Python concatenation of string and integer sum [duplicate]字符串和整数和的Python连接[重复]
【发布时间】:2024-01-21 18:02:02
【问题描述】:

我想打印数字总和和一些字符串,例如:

print("root: " + rootLeaf + " left:" + leftLeaf + "sum: " +(rootLeaf+leftLeaf) )

这里的“root”、“left”和“sum”是字符串,其中 rootLeaf 和 leftleaf 是整数,我想找到它们的总和。

我检查了post here,但我无法获得整数的总和 (字符串连接中的数学运算)

【问题讨论】:

标签: python string printing sum concatenation


【解决方案1】:
rootLeaf = 4
leftLeaf = 8
print("root: " + str(rootLeaf)+ " left: " + str(leftLeaf) + " sum: {}".format(rootLeaf + leftLeaf))

这是你的输出:

root: 4 left: 8 sum: 12

在 Python 中,为了打印整数,必须首先将它们转换为字符串。 .format 方法允许您将整数参数(两个叶子的总和)转换为字符串。您在需要字符串 {} 的位置输入一个占位符,然后在您的 .format 方法中指定该整数将是什么。在这种情况下,rootLeaf + leftLeaf。

【讨论】:

  • 为什么不进一步使用format,而不是str(rootLeaf)str(leftLeaf)
  • @CodeSurgeon 如果你愿意,你可以。我想在这个例子中简单地介绍 .format() 方法,但是你可以对所有你知道的整数值这样做。好点。
【解决方案2】:

如果您使用的是 Python 3,可以尝试使用.format


print("root: {0} left: {1} sum: {2}".format(rootLeaf, leftLeaf, rootLeaf+leftLeaf))

或者:


print("root: {}".format(rootLeaf), "left: {}".format(leftLeaf) , "sum: {}".format(rootLeaf+leftLeaf))

对于旧版本的 Python,您可以尝试使用%


# '+' can be replaced by comma as well
print("root: %s" % rootLeaf + " left: %s" % leftLeaf + " sum: %s" %(rootLeaf+leftLeaf)) 

或者:


print("root: %s left: %s sum: %s" % (rootLeaf, leftLeaf, rootLeaf+leftLeaf))

【讨论】:

    【解决方案3】:

    使用格式应该可以轻松处理所有类型。

    print("root: {} left: {} sum: {}".format(rootLeaf, rootRight, rootLeaf + rootRight))
    

    一般来说,请查看此网站了解更多详细信息:https://pyformat.info/

    【讨论】:

      【解决方案4】:

      您收到 TypeError 是因为您将字符串与整数连接起来。您首先需要将整数转换为字符串。您可以使用 str 函数执行此操作。

      在这种情况下

      print("root: " + str(rootLeaf) + " left:" + str(leftLeaf) + "sum: " +str(rootLeaf+leftLeaf))
      

      会打印你想要的。

      【讨论】: