字符串和变量的串联

时间:2015-09-01 19:47:32

标签: python string concatenation

我需要的是打印“1和2之和为3”。我不确定如何添加a和b,因为我得到一个错误或它说“a和b的总和是和”。

def sumDescription (a,b):
    sum = a + b
    return "the sum of" + a " and" + b + "is" sum

3 个答案:

答案 0 :(得分:3)

您无法将字符串连接到字符串,使用str.format并只传入参数a,b并使用+ b来获取总和:

def sumDescription (a,b): 
    return "the sum of {} and {} is {}".format(a,b, a+b)

sum也是内置函数,因此最好避免将其用作变量名。

如果要连接,则需要转换为str

def sumDescription (a,b):
   sm = a + b
   return "the sum of " + str(a) + " and " +  str(b) + " is " + str(sm)

答案 1 :(得分:2)

使用字符串插值,就像这样。 Python将在内部将数字转换为字符串。

def sumDescription(a,b):
    s = a + b
    d = "the sum of %s and %s is %s" % (a,b,s)

答案 2 :(得分:1)

您正在尝试连接stringint 您必须事先将int转为string

def sumDescription (a,b):
    sum = a + b
    return "the sum of " + str(a) + " and " + str(b) + " is " + str(sum)