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
CodePudding user response:
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]
CodePudding user response:
Use enumerate()
to get the index of each entry.
for idx,i in enumerate(t):
t[idx] = i.strip()
CodePudding user response:
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!
CodePudding user response:
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)