字符串和整数和的Python连接

2024-09-30 01:36:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

我检查了post here,但是我不能得到整数的和 (字符串合并中的数学运算)


Tags: 字符串here数字数学整数rootpostleft
3条回答

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

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

一般来说,在这个网站上可以看到更多的细节:https://pyformat.info/

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


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

或者:


^{pr2}$

对于旧版本的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))
rootLeaf = 4
leftLeaf = 8
print("root: " + str(rootLeaf)+ " left: " + str(leftLeaf) + " sum: {}".format(rootLeaf + leftLeaf))

以下是您的输出:

^{pr2}$

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

相关问题 更多 >

    热门问题