简体   繁体   中英

Remove unicode in Python from database?

I have a Flask website and I want to assign lists of values from an SQLite3 table to a variable. I managed to do this however every item in the list displays the value like this: [u'Chemistry'] however I just want it to display 'Chemistry'.

Here is my code:

cur = g.db.execute("SELECT DISTINCT subject FROM questions")
subjectList = [list(row) for row in cur.fetchall()]

I looked for answers which included using str() around row to convert into a string and changing the type of the value's column to Blob but neither work. How would I solve this? Thanks.

When you query SQLite, you will get a result that resembles

[('value 1',), ('value 2',)]

You then use a list comprehension, converting each record to a list. This gets you something like

[['value 1'], ['value 2']]

Instead, you probably want to extract the first item from each tuple in the result to get your desired list.

subjectList = [row[0] for row in cur.fetchall()]

This will get you

['value 1', 'value 2']

With this version of subjectList you can use the following in your template.

{% for subject in subjectList %}
    {{ subject }}
{% endfor %}

try using encode:

>>>a = u'test'
>>>a
u'test'
>>> a.encode('ascii')
'test'

your code:

subjectList = [list(row) for row in cur.fetchall()]

that list comprehension is casting the output as a list: list(row)
what about if you change it to

subjectList = [row.encode('ascii') for row in cur.fetchall()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM