Best way to clean up list items?
Jussi Piitulainen
jussi.piitulainen at helsinki.fi
Mon May 2 12:57:07 EDT 2016
DFS writes:
> Have: list1 = ['\r\n Item 1 ',' Item 2 ','\r\n ']
> Want: list1 = ['Item 1','Item 2']
>
>
> I wrote this, which works fine, but maybe it can be tidier?
>
> 1. list2 = [t.replace("\r\n", "") for t in list1] #remove \r\n
> 2. list3 = [t.strip(' ') for t in list2] #trim whitespace
> 3. list1 = filter(None, list3) #remove empty items
>
> After each step:
>
> 1. list2 = [' Item 1 ',' Item 2 ',' '] #remove \r\n
> 2. list3 = ['Item 1','Item 2',''] #trim whitespace
> 3. list1 = ['Item 1','Item 2'] #remove empty items
Try filter(None, (t.strip() for t in list1)). The default.
Funny-looking data you have.
More information about the Python-list
mailing list