【问题标题】:Python concatenation of string字符串的Python连接
【发布时间】:2013-08-20 19:07:14
【问题描述】:

我正在做 python 编程,这是其中的类单元。并且代码没有打印正确的答案。

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()

我正在尝试打印 这是一辆 88 MPG 的银色 DeLorean。

【问题讨论】:

  • 但是它打印了什么?
  • 考希克,还要加空格:'...self.color + " " +self.model...'

标签: python class concatenation


【解决方案1】:

试试这个版本的display_car 方法:

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

或者,您可以使用format

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

两个版本都打印This is a silver DeLorean with 88 MPG.

我认为您发现这两个版本都比字符串连接的版本更具可读性。

您可以通过使用带有命名参数的format 使其更具可读性:

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

另外,您也打印了None - 将print my_car.display_car() 替换为my_car.display_car()

【讨论】:

  • 更好地使用string.format() ?对于mpg,它应该是%d
  • @alecxe 我想知道我的连接语句是否正确?如果我想print 这是一辆 88 MPG 的银色 DeLorean 里面只有一个字一个接一个的空格
  • @GrijeshChauhan 是的,我使用format 添加了选项。 %d 在这里可能更正确,同意。谢谢。
  • @Kaushik 您的连接语句几乎是正确的,只是您缺少空格。最好使用我提到的选项 - 更少的错误提示和更多的可读性。
【解决方案2】:

改变这个:

def display_car(self):
    return "This is a "+ self.color + self.model+ " with "+str(self.mpg)+"MPG"

你看,display_car 方法必须返回要打印的值。或者,您可以保留 display_car() 原样,而是像这样调用方法:

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

【讨论】:

    【解决方案3】:

    print my_car.display_car() 中的 print 是多余的,因为您已经在 display_car 方法中打印了语句。因此,您会得到一个额外的None

    【讨论】:

    • 那我该怎么办? display_car 方法 print 语句应替换为 return?
    • 这是一种选择。或者,只写my_car.display_car()(前面没有print)。
    • 非常感谢@benjamin
    【解决方案4】:

    如果你不返回任何东西,Python 会隐式返回 None,所以 printing 调用 print 的函数也将 print None

    【讨论】:

      【解决方案5】:

      线

      print my_car.display_car()
      

      应该是

      my_car.display_car()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-11
        • 2011-03-23
        • 2016-03-14
        • 2013-03-20
        • 2010-09-27
        • 2017-12-18
        • 2011-05-09
        • 2020-12-30
        相关资源
        最近更新 更多