Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2 How to change list of unicode returned by values_list operation to list of strings

I performed this operation to retrieve a queryset:

Name.objects.values_list('name', flat=True)

And it returns these results:

[u'accelerate', u'acute', u'bear', u'big']

The results are all in unicode (u'). How do I remove them all so that I get the result:

['accelerate', 'acute', 'bear', 'big']
like image 771
jdtoh Avatar asked Feb 15 '13 13:02

jdtoh


2 Answers

If you want to encode in utf8, you can simply do:

definitions_list = [definition.encode("utf8") for definition in definitions.objects.values_list('title', flat=True)]
like image 165
tayfun Avatar answered Sep 18 '22 11:09

tayfun


You could call str on all the values (note that map is a bit lazy, list() added to immediately turn it back into an indexable object):

thingy = list(map(str, [u'accelerate', u'acute', u'bear', u'big']))

Or use a list comprehension:

[str(item) for item in [u'accelerate', u'acute', u'bear', u'big']]

In the end though, why would you require them to be str explicitly; added to a django template (like {{ value }}), the u's will disappear.

like image 37
akaIDIOT Avatar answered Sep 22 '22 11:09

akaIDIOT