How to remove the negative sign in a list?

Viewed 164

I'm trying to remove all the negative signs before index[2] in premier_league:

My code:

premier_league = [
             ['A1','Manchester City', '-1', 'Aguero'],
             ['A2','Manchester City', '-11,2', 'Mahrez'],
             ['A3','Manchester City', '-13,5', 'Sterling'],
             ['B1','Liverpool', '-,5', 'Mane'],
             ['B2','Liverpool', '-5,6', 'Salah'],
             ['B3','Liverpool', '-7,2', 'Jota']]

for l in premier_league:
    del l[-2][0]

Current output:

TypeError: 'str' object doesn't support item deletion

Desired output:

premier_league = [
             ['A1','Manchester City', '1', 'Aguero'],
             ['A2','Manchester City', '11,2', 'Mahrez'],
             ['A3','Manchester City', '13,5', 'Sterling'],
             ['B1','Liverpool', ',5', 'Mane'],
             ['B2','Liverpool', '5,6', 'Salah'],
             ['B3','Liverpool', '7,2', 'Jota']]
4 Answers

str.strip() will remove whitespace from either side of the string you call it on. You can optionally give it a string, and it will remove all of those characters from either side of the string.

Its derivatives, str.lstrip() and str.rstrip(), will do the same but only for the left or right end of the string, respectively. In this case, since you want to remove a minus sign from the front, str.lstrip() is the way to go.

for l in premier_league:
    l[2] = l[2].lstrip('-')

Use nested list comprehensions and re.sub:

import re
premier_league = [[re.sub(r'^-', '', item) for item in x] for x in premier_league]

You can use str.strip() or you can convert to list and slice the "-"

for l in premier_league:
    if l[2].startswith('-'): #not sure if all start with - or not
       temp=list(l[2])[1:] #convert to list and slice
       l[2]=''.join(temp) #to return it to string again

side note: I think Liverpool should be first in your list, always ;)

Try setting the value to its absolute value:

for l in premier_league:
   i = str(l[2]).replace(',','.')
   i = abs(i)
   i = i.replace('.',',')
   l[2] = float(i)

...but that I think about it, it looks like too much fuss so I suspect that lstriping the '-' might be easier

Related