Skip to content
Advertisement

.strip() on array using for loop in Python not working?

I’m trying to get rid of blankspace before and after an element in an array using .strip(), How do i get this to work correctly, I currently have :

ing1 = ['Nivea', 'Water,   GlyCerin, Caprylic/Capric Triglyceride, Squalane, Coco-Caprylate/ Caprate']

    ing1list = []
    for ele in ing1[1:]:
        ing1list.extend(ele.strip().lower().split(','))
    print(ing1list)

my output which is nearly right, but still has a space before the second element is:

['water', '     glycerin', ' caprylic/capric triglyceride', ' squalane', ' coco-caprylate/ caprate']

Advertisement

Answer

I believe you are stripping before splitting. You want to split before stripping.

ing1 = ['Nivea', 'Water,   GlyCerin, Caprylic/Capric Triglyceride, Squalane, Coco-Caprylate/ Caprate']

ing1list = []

for ele in ing1[1:]:
    sub_ele = ele.split(",")
    for ele2 in sub_ele:
        ing1list.append(ele2.strip().lower()) 

print(ing1list)

Output:

['nivea', 'water', 'glycerin', 'caprylic/capric triglyceride', 'squalane', 'coco-caprylate/ caprate']

Also, ing1 could probably be a string.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement