【问题标题】:python: cannot concatenate 'str' and 'long' objectspython:不能连接'str'和'long'对象
【发布时间】:2010-08-21 00:36:18
【问题描述】:

我正在尝试在 django 中设置一个选择字段,但我认为这不是 django 问题。选择字段采用 2 元组的可迭代(例如,列表或元组)作为该字段的选择。

这是我的代码:

self.fields['question_' + question.id] = forms.ChoiceField(
                label=question.label,
                help_text=question.description,
                required=question.answer_set.required,
                choices=[("fe", "a feat"), ("faaa", "sfwerwer")])

由于某种原因,我总是收到以下错误:

TypeError - cannot concatenate 'str' and 'long' objects

最后一行总是突出显示。

我不想连接任何东西。几乎不管我将“选择”参数的列表更改为什么,我都会收到此错误。

发生了什么事?

【问题讨论】:

  • 请注意“最后一行被突出显示”,因为它指向错误所在的整个多行语句。
  • 非常感谢大家。解决了它。

标签: python


【解决方案1】:

很可能它突出显示最后一行只是因为您将语句拆分为多行。

实际问题的修复很可能会改变

self.fields['question_' + question.id]

self.fields['question_' + str(question.id)]

由于您可以在 Python 解释器中快速测试,因此将字符串和数字相加是行不通的:

>>> 'hi' + 6

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    'hi' + 6
TypeError: cannot concatenate 'str' and 'int' objects
>>> 'hi' + str(6)
'hi6'

【讨论】:

    【解决方案2】:

    'question_' 是一个字符串,question.id 是一个长字符串。您不能连接两种不同类型的东西,您必须使用 str(question.id) 将 long 转换为字符串。

    【讨论】:

      【解决方案3】:

      可能question.id 是一个整数。试试

      self.fields['question_' + str(question.id)] = ...
      

      改为。

      【讨论】:

        【解决方案4】:
        self.fields['question_' + question.id]
        

        这看起来是个问题。试试

        "question_%f"%question.id
        

        "question_"+ str(question.id)
        

        【讨论】:

          【解决方案5】:

          这是在一行中做太多事情的问题 - 错误消息变得稍微没有帮助。如果你把它写成下面的问题会更容易找到

          question_id = 'question_' + question.id
          self.fields[question_id] = forms.ChoiceField(
                          label=question.label,
                          help_text=question.description,
                          required=question.answer_set.required,
                          choices=[("fe", "a feat"), ("faaa", "sfwerwer")])
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-04-06
            • 1970-01-01
            相关资源
            最近更新 更多