Home > OS >  Facing errors with string items merged with brackets and percentage
Facing errors with string items merged with brackets and percentage

Time:11-21

I created list with the following items:

x=['RX', '0(', '0%)', '2(', '0%)', '154018(', '99%)', '0(', '0%)', '0(', '0%)', '0(', '0%)']

I want to get as:

y=[0,2,154018,0,0,0] 

Can someone help with this?

CodePudding user response:

You can try to parse the elements of your list to int after stripping ( and add them to a new list:

x=['RX', '0(', '0%)', '2(', '0%)', '154018(', '99%)', '0(', '0%)', '0(', '0%)', '0(', '0%)']
y = []
for a in x:
   try:
      y.append(int(a.strip('(')))
   except:
      continue
print(y)

Output:

[0, 2, 154018, 0, 0, 0]
  • Related