removing commas between numbers and special characters in python
I have a list something like
['Scottish Investment Trust 2, 220 0.92, Financial Services – 6.97,% 750, 000, Ashmore 2, 554 1.06, 175, 000, Close Brothers 2, 704 1.12, 175, 704 1.12, 750, 000, IG Group 6, 034 2.50']
I am trying to remove commas between numbers and % using .replace()
and re.sub()
however it removes commas from all the places.
The list which I am trying to get should look like this.
['Scottish Investment Trust 2220, 0.92, Financial Services – 6.97% 750000, Ashmore 2554, 1.06, 175000, Close Brothers 2704, 1.12, 175704, 1.12, 750000, IG Group 6034, 2.50']
Trying to remove commas using .replace()
however this removes all commas
list2 = [s.replace(',', '') for s in highlights]
Trying to remove commas using re.sub()
however this also removes all commas.
list2 = ''.join(list1)
list2 = re.sub(',', '',list2)
How can it be done? Where exactly Am I making a mistake?
Solution 1:
The rules governing the process of getting from A->B are not clearly explained but can possibly be deduced from the sample input/output. This code does achieve that transformation but in the absence of a well-defined specification, it may not work in all cases.
ALIST = ['Scottish Investment Trust 2, 220 0.92, Financial Services – 6.97,% 750, 000, Ashmore 2, 554 1.06, 175, 000, Close Brothers 2, 704 1.12, 175, 704 1.12, 750, 000, IG Group 6, 034 2.50']
OLIST = []
for s in ALIST:
r = []
try:
token = iter(s.split())
while (t := next(token)):
if t.endswith(',%'):
r.append(t.replace(',', ''))
else:
if t.endswith(','):
try:
int(t[:-1])
n = next(token)
if n.endswith(','):
n = n[:-1]
t = t[:-1] + n + ','
except ValueError:
pass
r.append(t)
except StopIteration:
pass
OLIST.append(' '.join(r))
print(OLIST)
Output:
['Scottish Investment Trust 2220, 0.92, Financial Services – 6.97% 750000, Ashmore 2554, 1.06, 175000, Close Brothers 2704, 1.12, 175704, 1.12, 750000, IG Group 6034, 2.50']