[Tutor] Python "returning .split() without empty strings

Alan Gauld alan.gauld at yahoo.co.uk
Sat Oct 24 07:14:23 EDT 2020


On 24/10/2020 01:44, Chris C wrote:
> Hi all, I have a question regarding string operations.
> the following string needs to be chopped up, having the 0's dividing the
> data that I wanted, therefore the string here becomes
> 
> # run this
> string = '1111022220000333300044405550055'
> string = string.split('0')
> 
> # get this
> ['1111', '2222', '', '', '', '3333', '', '', '444', '555', '', '55']
> 
> # but I want it without the empty strings,

There are (at least) two ways to tackle this.
One is to do the split using regular expressions to select multiple 0's.

import re
string = '1111022220000333300044405550055'
key_list = re.split('0+',string)  #split on 1 or more 0s

The other is to use a map or generator expression to filter them out.
Given regex propensity for complicating things I'd usually go with a GE:

> key_list = list()
> for key in string :
> if key != '':
> key_list.append(key)

Which is what the above is in disguise...

key_list = [key for key in string if key]

It does the same work but is shorter and arguably more readable.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list