Converting comma-separated string to list [duplicate]

This question already has an answer here:

  • How to convert a string list into an integer in python

    6 answers

I want to store a list of integers as a field in my model. As there is no field provided for this by default in Django, I am doing it by using a CommaSeparatedIntegerField called x. In my view, I then take this string and create a list of integers from it. When a model instance is created with parameter n, I want x to be set to length n, with each element being set to zero.

Here’s the model:

class Foo(models.Model):
    id = models.IntegerField(default = 0)
    x = models.CommaSeparatedIntegerField(max_length = 10)

@classmethod
def create(cls, _id, n):
    user = cls(id = _id)
    user.class_num_shown = '0,' * n

Then I create an instance:

f = Foo.create(1, 4)
f.save()

And load it from the database and convert the string into a list:

f = Foo.objects.get(id = 1)
x_string = f.x
x_list = x_string.split(',')
print x_list

But this outputs [u'0,0,0,0,'] rather than what I want, which would be [0,0,0,0]. How can I achieve my desired output?

Best answer

The separator argument for split() is not a list of different characters to split on, but rather the entire delimiter. Your code will only split occurrences of “comma space”.

Further, if you want integers instead of substrings, you need to do that conversion.

Finally, because you have a trailing comma, you need to filter empty results from your split.

>>> data = '0,0,0,0,'
>>> values = [int(x) for x in data.split(',') if x]
>>> values
[0, 0, 0, 0]