Python将布尔值连接到字符串不起作用

阿萨夫尔

作为程序的一部分,我编写了以下方法(隐藏的是一个布尔变量)。它位于一个名为 的对象中Deltext,该对象继承了一个名为 的类型DelMsginfo_msg()在其父类型中覆盖并使用类似的方法。

def info_msg(self):
    info = DelMsg.info_msg(self)
    if self.code == 'l':  # If message is long message
        return info + '#' + str(len(self.content)) + '#' + str(self.hidden)
    elif self.code == 'm':  # If message is snap message
        return info + '#' + str(self.timeout) + '#' + self.content
    else:  # If message is a normal message
        return info + '#' + self.content + '#' + str(self.hidden)

但是每次我调用该方法(从对象实例)时,它都会显示一个错误:TypeError: cannot concatenate 'str' and 'bool' objects,并说错误在最后一行,即使hidden被解析为字符串。

有没有办法在不使用条件的情况下解决这个问题?

穆罕默德·阿里·贾马维

以下是您可以继续调试代码的方法:

  1. 检查变量的类型:

编辑您的代码以包含以下内容 print(type(variable))

def info_msg(self):
    print(type(info))
    print(type(self.content))
    return info + '#' + self.content + '#' + str(self.hidden)

然后,运行程序并查看哪个其他变量是布尔值。

  1. 添加str(...)到布尔变量

最多,所有变量都是布尔类型,因此您可以按如下方式编辑代码:

def info_msg(self):
    return str(info) + '#' + str(self.content) + '#' + str(self.hidden)

另一种选择是使用str.format,它将负责将变量转换为字符串:

def info_msg(self):
    return "{0}#{1}#{2}".format(info, self.content, self.hidden)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章