Removing whitespace from each value in a list

Question:

I want to write a function where I remove whitespace from the front and back of each string in a list.

This is my list called t:

['Specialty Food',
 ' Restaurants',
 ' Dim Sum',
 ' Imported Food',
 ' Food',
 ' Chinese',
 ' Ethnic Food',
 ' Seafood']

When I use t[4].strip(), I get the result of ‘Imported Food’. Okay, whitespace in the front removed successfully – great.

Now, when I try to do the same for each value in the list in a for loop, I get an error. I don’t understand why.

This is my for loop:

for i in t:
    t[i] = i.strip()

This is my error:

TypeError                                 
Traceback (most recent call last)
Input In [204], in <cell line: 1>()
      1 for i in t:
----> 2     t[i] = i.strip()
TypeError: list indices must be integers or slices, not str
Asked By: nadiyast

||

Answers:

Use enumerate() to get the index of each entry.

for idx,i in enumerate(t):
    t[idx] = i.strip()
Answered By: Rob Heiser

for i in t: says "Loop through my list called t and assign each value to variable i". i through each iteration will take string values stored in the list. So t[i] doesn’t make any sense.

For instance the fist iteration would be

 t['Specialty Food'] = 'Specialty Food'

List indexes must be integers or slices, and the string 'Specialty Food' in t['Specialty Food'] is not an integer nor a slice.

Instead consider list comprehension:

t = [i.strip() for i in t]
Answered By: JNevill

Thank you JNevill, your comment pointed out a flaw in my coding logic.

I fixed the for loop:

for i in range(len(t)):
    t[i] = t[i].strip()

My code is no longer producing an error and I’m getting the desired result, which is the following list with no whitespaces in the front or back of each string:

['Specialty Food',
 'Restaurants',
 'Dim Sum',
 'Imported Food',
 'Food',
 'Chinese',
 'Ethnic Food',
 'Seafood']

Thank you everyone!

Answered By: nadiyast

If you want to stay away from indices and in-place mutations, I would suggest you use some functional aspects of Python to do the same operation.

t = ['Specialty Food', ' Restaurants', ' Dim Sum', ' Imported Food', ' Food', ' Chinese', ' Ethnic Food', ' Seafood']
new_t = map(lambda x: x.strip(), t)
print(new_t)
Answered By: user19696317
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.