Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove extra ',' in tuple in django(python)

Tags:

python

django

I have one problem in building a list of id using django. if i choose more than 1 id it ok but if i choose only one it will produce extra ',' in list.

testa = tuple([k['id'] for k in queryset.values('id')])
print testa

if in the queryset have exactly 1 id, it will display

(1234,)

other than that it ok

(1234,1244)

How can i remove extra ', in list'

like image 653
Najmi Avatar asked May 21 '11 13:05

Najmi


2 Answers

(1234,)

is the correct Python representation of a 1-tuple. (1234) would be wrong as that is taken as a simple integer in mathematical parentheses, evaluating to 1234, not a tuple containing it.

This is different for lists because the square brackets don't have this double purpose of also meaning mathemtical order-of-operations, so whilst [1234] and [1234,] are both valid representations of a length-1-list, the default textual representation can be without the extra comma.

If you are devising your own textual representation of a tuple that does not need to be the same as Python's, you could do eg.:

'(%s)' % ', '.join(map(repr, testa))
like image 184
bobince Avatar answered Sep 22 '22 07:09

bobince


To write a tuple containing a single value you have to include a comma, even though there is only one value.

You can index the tuple to get the desired output:

print testa[0]
>>>> 1234
like image 43
garnertb Avatar answered Sep 24 '22 07:09

garnertb