0

Currently, I'm working on a list like this

txt=['S&P 500 Index', '2,905.03', '+4.58', '+0.16%']                                  

Since I need to convert all the numerical value into float rather than str, in order to use float(), I have to get rid of ',' and '%'. Is there a smart way to do this in a line?

Now,I'm doing stuff like this. Change everything by finding the exact index.

txt[1]=txt[1].replace(",","")               
txt[3]=txt[3].replace("%","")  

I would like to see something like this

['S&P 500 Index', '2905.03', '+4.58', '+0.16']
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219

1 Answers1

1

If the first element may not contain % or , you can apply the replace operations on it too without changing its value.

txt=['S&P 500 Index', '2,905.03', '+4.58', '+0.16%']                                  
txt = [s.replace('%', '').replace(',','') for s in txt]
print(txt)
rdas
  • 20,604
  • 6
  • 33
  • 46