Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove all strings that fit certain format from a list?

Question: Say I have a list a = ['abd', ' the dog', '4:45 AM', '1234 total', 'etc...','6:31 PM', '2:36']

How can I go about removing elements such as 4:45 AM and 6:31 PM and '2:36'? i.e, how can I remove elements of the form number:number|number and those with AM/PM on the end?

To be honest, I havent tried much, as I am not sure really where to even begin, other than something like:

[x for x in a if x != something]
like image 680
cjg123 Avatar asked Dec 06 '18 20:12

cjg123


1 Answers

You can use regular expression \d+(?::\d+)?$ and filter using it.

See demo.

https://regex101.com/r/HoGZYh/1

import re
a = ['abd', ' the dog', '4:45', '1234 total', '123', '6:31']
print [i for i in a if not re.match(r"\d+(?::\d+)?$", i)]

Output: ['abd', ' the dog', '1234 total']

like image 134
vks Avatar answered Oct 23 '22 12:10

vks