I have a list of filenames in Python that looks like this, except that the list is 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 the filename strings in 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 (indicated in the list of filenames) 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!