How do I clean this 2D list:
sales1=[[' Andy Turner ',' $62 ', ' \n 25/12/21], ['Kelvin Obgona ', ' $120 ', ' \n 01/03/22 ']]
into:
[['Andy Turner','$62','25/12/21], ['Kelvin Obgona', '$120', '01/03/22']]
My code:
sales_clean=[]
for t1 in list1:
sales_clean.append(sales1.strip())
AttributeError: 'list' object has no attribute 'strip'
Thanks for helping.
CodePudding user response:
You need to apply str.strip
to each item of the list. You can use a list comprehension instead.
sales_clean = [[s.strip() for s in m] for m in sales1]
This is equivalent to the following using only loops.
sales_clean=[]
for t1 in sales1:
t_clean = []
for t2 in t1:
t_clean.append(t2.strip())
sales_clean.append(t_clean)
CodePudding user response:
sales1=[[' Andy Turner ',' $62 ', ' \n 25/12/21'], ['Kelvin Obgona ', ' $120 ', ' \n 01/03/22 ']]
#Strip spaces from 2D array the left and right of the string
for i in range(len(sales1)):
for j in range(len(sales1[i])):
sales1[i][j]=sales1[i][j].strip()
print(sales1)
or faster
sales2=[[x.strip() for x in y] for y in sales1]