Python3 filter/remove strings of a list

Viewed 61

i grabed some data and stuff with my crawler and now i have to analyse them.

I got a list with different links of some pictures, but i just want to save the ones without "/Thumbnails"

pictures = ['Media/Shop/922180cruv.jpg', 'Media/Shop/922180cruvdet.jpg', 'Media/Shop/Thumbnails/922180cruvx320x240.jpg', 'Media/Shop/Thumbnails/922180cruvdetx320x240.jpg']

Is there a way to say "if string got /Thumbnails", remove all from the list?. I got a csv with ~25000 list in separate columns.

Already tried with remove() and indexing, but my lists are different, so the index for the first list wont fit to the second list for example

3 Answers

Use filtering list comprehension:

pictures = ['Media/Shop/922180cruv.jpg', 'Media/Shop/922180cruvdet.jpg', 'Media/Shop/Thumbnails/922180cruvx320x240.jpg', 'Media/Shop/Thumbnails/922180cruvdetx320x240.jpg']

pictures = [p for p in pictures if not "/Thumbnails/" in p]

print(pictures)

Prints:

['Media/Shop/922180cruv.jpg', 'Media/Shop/922180cruvdet.jpg']

You can user split and join feature of python as below.

pictures = ['Media/Shop/922180cruv.jpg', 'Media/Shop/922180cruvdet.jpg', 
            'Media/Shop/Thumbnails/922180cruvx320x240.jpg', 
            'Media/Shop/Thumbnails/922180cruvdetx320x240.jpg']
pictures2= []
for pic in pictures:
  if "Thumbnails" in pic:
    pic_list = pic.split("Thumbnails/")
    pic = "".join(pic_list) 
    print(pic)
    pictures2.append(pic)
  else:
    pictures2.append(pic)
print(pictures2)

output

['Media/Shop/922180cruv.jpg', 'Media/Shop/922180cruvdet.jpg', 'Media/Shop/922180cruvx320x240.jpg', 'Media/Shop/922180cruvdetx320x240.jpg']

You can iterate through the list and check if each string contains the substring /Thumbnail

result   = []
pictures = ['Media/Shop/922180cruv.jpg', 'Media/Shop/922180cruvdet.jpg', 
            'Media/Shop/Thumbnails/922180cruvx320x240.jpg', 
            'Media/Shop/Thumbnails/922180cruvdetx320x240.jpg']


for picture in pictures:
    if picture.find('/Thumbnails') == -1:
        result.append(picture)

Output:

['Media/Shop/922180cruv.jpg', 'Media/Shop/922180cruvdet.jpg']

Demo: https://onlinegdb.com/rkAo1EL4w

Related