StayAheadOfLife
StayAheadOfLife

Reputation: 55

Python - String Splitting

Writing '1000011'.split('1') gives

['', '0000', '', '']

What I want is:

['1', '0000', '11']

How do I achieve this?

Upvotes: 1

Views: 66

Answers (2)

vaultah
vaultah

Reputation: 46523

The str.split(sep) method does not add the sep delimiter to the output list.

You want to group string characters e.g. using itertools.groupby:

In:  import itertools

In:  [''.join(g) for _, g in itertools.groupby('1000011')]
Out: ['1', '0000', '11']

We didn't specify the key argument and the default key function just returns the element unchanged. g is then the group of key characters.

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107287

You can use regex :

>>> re.findall(r'0+|1+','1000011')
['1', '0000', '11']

Upvotes: 0

Related Questions