Remove 'u' from a python list

use [str(item) for item in list]

example

>>> li = [u'a', u'b', u'c', u'd']
>>> print li
[u'a', u'b', u'c', u'd']
>>> li_u_removed = [str(i) for i in li]
>>> print li_u_removed
['a', 'b', 'c', 'd']

The u means a unicode string which should be perfectly fine to use. But if you want to convert unicode to str (which just represents plain bytes in Python 2) then you may encode it using a character encoding such as utf-8.

>>> items = [u'[190215]']
>>> [item.encode('utf-8') for item in items]
['[190215]']

In your current code, you are iterating on a string, which represents a list, hence you get the individual characters.

>>> from ast import literal_eval
>>> l = [u'[190215]']
>>> l = [item for value in l for item in value]
>>> l
[u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']

Seems to me, you want to convert the inner string representation of list, to a flattened list, so here you go:

>>> l = [u'[190215]']
>>> l = [item for value in l for item in literal_eval(value)]
>>> l
[190215]

The above will work only when all the inner lists are strings:

>>> l = [u'[190215]', u'[190216, 190217]']
>>> l = [item for value in l for item in literal_eval(value)]
>>> l
[190215, 190216, 190217]
>>> l = [u'[190215]', u'[190216, 190217]', [12, 12]]
>>> l = [item for value in l for item in literal_eval(value)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/ast.py", line 80, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib/python2.7/ast.py", line 79, in _convert
    raise ValueError('malformed string')
ValueError: malformed string

Tags:

Python