Best way to clean up list items?
justin walters
walters.justin01 at gmail.com
Mon May 2 13:10:02 EDT 2016
On May 2, 2016 10:03 AM, "Jussi Piitulainen" <jussi.piitulainen at helsinki.fi>
wrote:
>
> 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
You could also try compiled regex to remove unwanted characters.
Then loop through the list and do a replace for each item.
More information about the Python-list
mailing list