How to return string with the variable concatenated?


#1

I’m having trouble returning a string concatenated with variables.

One of the possible solutions is

color = "Sliver"
model = "XUV"
mpg = 88

return "This is a " + color + " " + model + " with " + str(mpg) + " MPG."

But as long as I write the following code it is good, but when I’m returning it, it is not returned as a string, instead, it is returning a list

print  "This is a ",color,model,"with",str(mpg),"MPG"  #This is printing it as string
s = "This is a ",color,model,"with",str(mpg),"MPG" #This is printing it as  
print s  #This is printing a list

Can someone tell me the better way of returning the string with the variables concatenated?


#2

Python 2 formatting is the expected norm. Use a single string with interpolated variables.

print "This is a %s %s with %s MPG" % (color, model, mpg)

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.