簡體   English   中英

刪除 python 中數字和特殊字符之間的逗號

[英]removing commas between numbers and special characters in python

我有一個類似的清單

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

我正在嘗試使用.replace()re.sub()刪除數字和 % 之間的逗號,但是它會從所有地方刪除逗號。

我想要得到的列表應該是這樣的。

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

嘗試使用.replace()刪除逗號,但這會刪除所有逗號

list2 = [s.replace(',', '') for s in highlights]

嘗試使用re.sub()刪除逗號,但這也會刪除所有逗號。

list2 = ''.join(list1)
list2 = re.sub(',', '',list2)

怎么做到呢? 我到底在哪里犯了錯誤?

控制從 A->B 獲取過程的規則沒有明確解釋,但可以從樣本輸入/輸出中推斷出來。 此代碼確實實現了這種轉換,但在沒有明確定義的規范的情況下,它可能無法在所有情況下工作。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM