How to split a list item into two?

If I have data stored in a list, for example

images = ['pdf-one','gif-two','jpg-three']

How to break them into several elements in a hyphen - not subscriptions. I.e.

images = ['pdf','-one','gif','-two','jpg','-three']

not

images = [['pdf','-one'],['gif','-two'],['jpg','-three']]
+3
source share
2 answers

In this case, splitting with a regular expression makes the code the most readable:

import re

hyphensplit = re.compile('(-[a-z]+)').split
images = [part for img in images for part in hyphensplit(img) if part]

Demo:

>>> import re
>>> hyphensplit = re.compile('(-[a-z]+)').split
>>> images = ['pdf-one','gif-two','jpg-three']
>>> [part for img in images for part in hyphensplit(img) if part]
['pdf', '-one', 'gif', '-two', 'jpg', '-three']
+5
source

You can use str.partitionfor this:

>>> from itertools import chain
>>> images = ['pdf-one', 'gif-two', 'jpg-three']
>>> list(chain.from_iterable([[a, b+c] for a, b, c 
                                            in (x.partition('-') for x in images)]))
['pdf', '-one', 'gif', '-two', 'jpg', '-three']

Using the generator function for a more readable solution:

def my_split(seq):
    for item in seq:
        a, b, c = item.partition('-')
        yield a
        yield b+c

>>> list(my_split(images))
['pdf', '-one', 'gif', '-two', 'jpg', '-three']
+4
source

All Articles