If I have data stored in a list, e.g.
images = ['pdf-one','gif-two','jpg-three']
How do I split these into multiple elements at the hyphen - not sublists. I.e.
images = ['pdf','-one','gif','-two','jpg','-three']
not
images = [['pdf','-one'],['gif','-two'],['jpg','-three']]
Create an empty list that will store the quotients. Iterate across all the elements in the given list using a for loop. Divide each element with the given number/divisor and append the result in the resultant list. Finally, display the resultant list after all the quotients have been calculated and appended to it.
Usually, we use a comma to separate three items or more in a list. However, if one or more of these items contain commas, then you should use a semicolon, instead of a comma, to separate the items and avoid potential confusion.
To trim in-place, use del on a slice; e.g. del listobj[-x:] will remove the last x elements from the list object.
In this case splitting with a regex makes for the most readable code:
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With