Home > Software engineering >  I have list of strings and I want to remove symbols and split it
I have list of strings and I want to remove symbols and split it

Time:01-06

I have this list:

['-- - --', '$449\n          - \n          $571', '12%', '48,090', '132%', '$406']

I want to get this output:

['', 449, 571, 12, 48090, 132, 406]

Ive tried to use regex but without success :( I couldn't split the 2nd place ['$449\n - \n $571'] to [449, 571]

one problem is that the string '-- - --' wont always be on the 1st place

Thanks for the help in advanced

CodePudding user response:

We can use re.findall here and iterate the list for a regex approach:

lst = ['-- - --', '$449\n          - \n          $571', '12%', '48,090', '132%', '$406']
matches = []
for item in lst:
    if re.search(r'\d', item):
        result = re.findall(r'\d{1,3}(?:,\d{3})*|\d ', item)
        for r in result:
            matches.append(r)
    else:
        matches.append('')

print(matches)
# ['', '449', '571', '12', '48,090', '132', '406']

CodePudding user response:

Here is an alternative using comprehensions and regular expressions:

>>>import re
>>> l = ['-- - --', '$449\n          - \n          $571', '12%', '48,090', '132%', '$406']
>>> l = [re.findall(r'\d ', _.replace(',', '')) for _ in l]
>>> l
[[], ['449', '571'], ['12'], ['48090'], ['132'], ['406']]
>>> 
  •  Tags:  
  • Related