Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting comma-separated string to list [duplicate]

Tags:

python

django

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?

like image 815
Karnivaurus Avatar asked Jul 03 '14 14:07

Karnivaurus


1 Answers

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]
like image 90
FogleBird Avatar answered Sep 18 '22 01:09

FogleBird