如何将字符串和变量分配给变量

时间:2017-01-15 18:55:13

标签: python string variables object

class Bird:
    def __init__(self):
        self.noise = "chirping"
        self.beak = "closed"
        self.wings = "closed"
    def __str__(self):
        msg = "The bird is ", self.noise "its beak is ", 
               self.beak "its wings are ", self.wings
        return msg
mybird = Bird()
print(mybird)

我不完全确定问题是什么,但我需要这个来打印我的Bird对象。

这是python给我的错误:

Traceback (most recent call last):

  File "D:/000- Python-Coding/Practice/ bird object program.py", line 10, in <module>

   print(mybird)

TypeError: __str__ returned non-string (type tuple)

6 个答案:

答案 0 :(得分:3)

如错误消息所述:

"__r_"

你正在构建一个元组而不是字符串,所以我建议使用字符串格式,如下所示:

TypeError: __str__ returned non-string (type tuple)

答案 1 :(得分:1)

您可以添加+字符串:

msg = "The bird is " + self.noise + " its beak is " + self.beak + " its wings are " + self.wings

答案 2 :(得分:1)

TypeError: __str__ returned non-string (type tuple)

告诉你一切。

        msg = "The bird is ", self.noise "its beak is ", self.beak "its wings are ", self.wings

如上所述用逗号分隔会创建一个元组(item1 , item2 , ...)

你想要的是带有+的字符串连接或字符串格式,如其他答案所示。

答案 3 :(得分:0)

使用它+来连接字符串:

 msg = "The bird is " + self.noise + "its beak is " + self.beak + "its wings are " + self.wings

所以它看起来像这样:

class Bird:
    def __init__(self):
        self.noise = "chirping"
        self.beak = "closed"
        self.wings = "closed"
    def __str__(self):
        msg = "The bird is " + self.noise + "its beak is " + self.beak + "its wings are " + self.wings
        return msg
mybird = Bird()
print(mybird)

输出:

The bird is chirpingits beak is closedits wings are closed

答案 4 :(得分:0)

问题是msg不是str(字符串),而是元组。事实上:

msg = "The bird is ", self.noise "its beak is ", self.beak "its wings are ", self.wings

是逗号分隔的表达式列表,Python将其解释为:

msg = ("The bird is ", self.noise "its beak is ", self.beak "its wings are ", self.wings)

您可能想要的是使用加号(+)运算符追加您可以执行的部分:

msg = "The bird is "+self.noise+" its beak is "+self.beak+" its wings are "+self.wings

或者您可以使用string formatting

msg = "The bird is %s its beak is %s its wings are "%(self.noise,self.beak,self.wings)

答案 5 :(得分:0)

您需要从noise = "chirping" beak = "closed" wings = "close" msg = "The bird is ", noise, "its beak is ", beak, "its wings are ", wings type(msg) # <class 'tuple'> msg = "The bird is "+ noise+ "its beak is "+ beak+ "its wings are "+ wings type(msg) # <class 'str'> fucntion:

返回字符串
tableView.visibleCells