Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

python - How to remove the negative sign in a list?

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']]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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('-')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...