Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract string in list based on character in Python

I have a list in Python that looks like this except much longer:

filenames = ['BETON\\map (120).png',
 'BETON\\map (125).png',
 'BETON\\map (134).png',
 'BETON\\map (137).png',
 'TUILES\\map (885).png',
 'TUILES\\map (892).png',
 'TUILES\\map (924).png',
 'TUILES\\map (936).png',
 'TUILES\\map (954).png',
 'TUILES\\map (957).png',
 'TUILES\\map (97).png',
 'TUILES\\map (974).png',
 'TUILES\\map (987).png']

I would like to only keep the first part of my list in order to only keep its type, like so:

filenames = ['BETON',
     'BETON',
     'BETON',
     'BETON',
     'TUILES',
     'TUILES',
     'TUILES',
     'TUILES',
     'TUILES',
     'TUILES',
     'TUILES',
     'TUILES',
     'TUILES']

I have been using a workaround grabbing the first 5 elements

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def Extract(files):
    return [item[:5] for item in files]
     
# Driver code
files2 = Extract(files)

However it’s becoming an issue as I have many more types coming with varying lengths in and I cannot just take the first elements. How can I extract as soon as it spots the backslash \ ?

Many thanks!

>Solution :

Split the filenames on a backslash, and take only the first item from the split.

filenames = [n.split('\\')[0] for n in filenames]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading