Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python concatenation of string

I'm doing python programming and this is class unit of that. and the code is not printing the right answer.

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg
    def display_car(self):
        print "This is a "+ self.color + self.model+ " with "+str(self.mpg)+"MPG"

my_car = Car("DeLorean", "silver", 88)
print my_car.display_car()

I'm trying to print This is a silver DeLorean with 88 MPG.


1 Answers

Try this version of display_car method instead:

def display_car(self):
    print "This is a %s %s with %d MPG." % (self.color, self.model, self.mpg)

Or, you can make use of format:

def display_car(self):
    print "This is a {0} {1} with {2} MPG.".format(self.color, self.model, self.mpg)

Both versions print This is a silver DeLorean with 88 MPG.

I think you see that both versions are more readable than your's with string concatenation.

You can make it even more readable by using format with named arguments:

def display_car(self):
    print "This is a {color} {model} with {mpg} MPG.".format(color=self.color, model=self.model, mpg=self.mpg)

Also, you have None printed too - replace print my_car.display_car() with my_car.display_car().

like image 90
alecxe Avatar answered Sep 29 '26 19:09

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!