Search code examples
pythonpython-3.xlistappendstrip

Python stripping characters and combine list objects


I have a massive list that looks similar to this:

['red.color\xa0', '2020-11-27\xa0', 'green.color\xa0', '2020-11-27\xa0', 'blue.color\xa0', '2020-11-27\xa0']
 

I'm trying to figure out how to strip the \xa0 characters out as well as combine every two list items, so it would end up like:

[['red.color', '2020-11-27'], ['green.color', '2020-11-27'], ['blue.color', '2020-11-27']]

I tried this, but failed miserably:

for data in ugly:
    data = data.strip("\xa0")

As for combining every other list item into a new list, well, if I fail at the above you can probably guess I implode at this.


Solution

  • \xa0 is actually non-breaking space. Replace it like below using List Comprehension:

    In [3731]: ugly = ['red.color\xa0', '2020-11-27\xa0', 'green.color\xa0', '2020-11-27\xa0', 'blue.color\xa0', '2020-11-27\xa0']
    In [3736]: x = [i.replace(u'\xa0', u'') for i in ugly]
    

    Now, combine every 2 elements of list using zip:

    In [3741]: y = [list(i) for i in zip(x[0::2], x[1::2])]
    In [3742]: y
    Out[3742]: 
    [['red.color', '2020-11-27'],
     ['green.color', '2020-11-27'],
     ['blue.color', '2020-11-27']]