Python 字符串和变量的串联

Python 字符串和变量的串联,python,string,concatenation,Python,String,Concatenation,我需要的是打印“1和2的和是3”。我不知道如何加a和b,因为我要么得到一个错误,要么它说“a和b的和就是和” 您不能将整数合并为字符串,请使用str.format,只需传入参数a、b,然后使用a+b来获得总和: def sumDescription (a,b): return "the sum of {} and {} is {}".format(a,b, a+b) sum也是一个内置函数,因此最好避免将其用作变量名 如果要连接,则需要强制转换为str: def sumDescrip

我需要的是打印“1和2的和是3”。我不知道如何加a和b,因为我要么得到一个错误,要么它说“a和b的和就是和”


您不能将整数合并为字符串,请使用
str.format
,只需传入参数a、b,然后使用a+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)

您不能将整数合并为字符串,请使用
str.format
,只需传入参数a、b,然后使用a+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)

您正在尝试连接
字符串
int

您必须先将
int
转换为
string

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

您正在尝试连接
字符串
int

您必须先将
int
转换为
string

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

使用字符串插值,如下所示。Python将在内部将数字转换为字符串

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

使用字符串插值,如下所示。Python将在内部将数字转换为字符串

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

sumsdescription(1.5,4)->1和4的总和是5
touch。我想使用字符串表示法是可行的,因为Python会自动使用str()将int/float转换为stringyep,使用
%f
也会给出不同的输出,str.format只会让生活更简单
sumsdescription(1.5,4)->1和4的总和是5
Touche。我想使用字符串表示法是可行的,因为Python会自动使用str()将int/float转换为stringyep,使用
%f
也会给出不同的输出,str.format只会让生活更简单