Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: cannot concatenate 'str' and 'long' objects

Tags:

I'm trying to set up a choice field in django, but I don't think this is a django issue. The choices field takes an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field.

Here's my code:

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")])

for some reason, i always get the following error:

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

The last line is always highlighted.

I'm not trying to concatenate anything. Almost regardless of what I change the list to for the 'choices' parameter, I get this error.

What's going on?

like image 561
Roger Avatar asked Aug 20 '10 16:08

Roger


People also ask

Why can't Python concatenate str and int objects?

In Python, we cannot concatenate a string and an integer together. They have a different base and memory space as they are completely different data structures.

Why can't I concatenate in Python?

Python does not support the auto type of the variable to be cast. You can not concatenate an integer value to a string. The root cause of this issue is due to the concatenation between an integer value and a string object. Before concatenation, an integer value should be converted to a string object.

Can only concatenate str not NoneType to str Python?

The Python "TypeError: can only concatenate str (not "NoneType") to str" occurs when we try to concatenate a string and a None value. To solve the error, correct the assignment or check if the variable doesn't store a None value before concatenating.


2 Answers

Most likely it's highlighting the last line only because you split the statement over multiple lines.

The fix for the actual problem will most likely be changing

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

to

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

As you can quickly test in a Python interpreter, adding a string and a number together doesn't work:

>>> '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'
like image 119
Mark Rushakoff Avatar answered Sep 27 '22 19:09

Mark Rushakoff


'question_' is a string, question.id is a long. You can not concatenate two things of different types, you will have to convert the long to a string using str(question.id).

like image 28
Sjoerd Avatar answered Sep 27 '22 19:09

Sjoerd