Home > Back-end >  Extract string in list based on character in Python
Extract string in list based on character in Python

Time:01-22

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

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!

CodePudding user response:

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

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

CodePudding user response:

string.split()

Yeah, you indeed can split every string and take only the part you need.

Try this:

for index in range(len(filenames)):
    # Only take the name
    filenames[index] = filenames[index].split('\\')[0]

This code above doesn't distingues by file name lenght but it just take the string before the character you pass to the split function. '\' in your case.

  • Related