samu101108
samu101108

Reputation: 775

Delete a pattern that is in a list from inside a string in Python

Well, I have a string:

string ="01. 01 22 3 456 0001 02 . 002 3. 0003 4 . 0004 05- 0005 06 - 0006 7- 0007 8 - 0008 09. 0009 10. 0010"

And as you see it is a list. The important is just the number/numbers after the dot or hifen. And each number or group of numbers have to become an item in a list like that:

["01", "22", "3", "456", "0001", "002", "0003", "0004"....etc]

I worked something around regular expressions and I got this list :

['01.', '02 .', '3.', '4 .', '09.', '10.', '05-', '06 -', '7-', '8 -']

Now I need to remove it from there. The fist is type str and the second is type list, I coudn't figure out which method to use to solve it.

Any ideas?

Upvotes: 0

Views: 63

Answers (1)

Ajax1234
Ajax1234

Reputation: 71461

You can use re.findall:

import re
string ="01. 01 22 3 456 0001 02 . 002 3. 0003 4 . 0004 05- 0005 06 - 0006 7- 0007 8 - 0008 09. 0009 10. 0010"
results = re.findall('(?<=\s)\d+(?=\s[\d$])|(?<=\s)\d+(?=$)', string)

Output:

['01', '22', '3', '456', '0001', '002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010']

Upvotes: 2

Related Questions