【问题标题】:Python concatenating boolean to string doesn't workPython将布尔值连接到字符串不起作用
【发布时间】:2018-04-04 20:19:15
【问题描述】:

作为程序的一部分,我编写了以下方法(隐藏的是布尔变量)。它位于一个名为Deltext 的对象中,该对象继承了一个名为DelMsg 的类型。 info_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 被解析为字符串。

有什么方法可以在不使用条件的情况下解决这个问题?

【问题讨论】:

  • 使用 type(...) 检查其他两个变量的类型,如果其中一个是布尔型,也应用 str(..)。
  • 在 return 语句中为 all 添加 str()
  • 您可以将 contentinfo 转换为 str 而无需检查您是否希望它是布尔值或字符串以外的任何其他格式。
  • 我厌倦了投射其他的(虽然都是字符串)但它显示了相同的错误
  • 你能发布更多你的代码吗?你确定错误发生在这一行吗?

标签: python string boolean concatenation


【解决方案1】:

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

  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)

【讨论】:

    【解决方案2】:

    infocontent 可能也是布尔值。你可以克服这个

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

    【讨论】:

    • 我已经尝试过这样做,虽然它们都是字符串,并且一直显示相同的消息
    • 你一定漏掉了什么。我已经尝试过将所有项目都设为布尔值的这段代码,并且它有效。等等,我更新了它以匹配类实例
    猜你喜欢
    • 2012-08-10
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    相关资源
    最近更新 更多