Douglas da Dias Silva
Douglas da Dias Silva

Reputation: 1230

Removing elements from a string within a list

I have a list consisting of dictionaries converted to string, each slot in that list is as follows '{< Candidate: Candidate1 >: 1.5}'

I want to remove all non-alphanumeric and ':' elements, so they look like this:

'Candidate: Candidate1: 1.5'

I tried to do the following:

for l in list:
        for l2 in l:
                if l2.isalnum()==False or l2==':':
                        l2.replace("")

But I did not get the desired result, how can I do this?

Thanks in advance

Upvotes: 0

Views: 30

Answers (1)

dawg
dawg

Reputation: 103884

Given:

>>> li=[ '{: 1.5}',  '{: 1.6}']

You can use a element by element regex:

>>> [re.sub(r'[^\w\d.]+',"",e) for e in li]
['1.5', '1.6']

Edit

If you want to keep the : you can do:

>>> [re.sub(r'[^\w\d.:]+',"",e) for e in li]
[':1.5', ':1.6']

Upvotes: 1

Related Questions