0

I've a long list of strings; they are basically filenames. The format is like:

["abcdedf_023.txt",
 "foeoioo_011.txt", 
 "sdjskdsjd_3131.txt", 
 "dsdsdsrer_044.txt", 
 "rgfbfgrt_12.txt"]

and so on.

What I need is to filter out the names containing numbers greater than 15 at the end. So with the above input, the desired outout would be:

["abcdedf_023.txt",
 "sdjskdsjd_3131.txt", 
 "dsdsdsrer_044.txt"] 

This number (15) is not fixed and provided by user as input.

2 Answers 2

5

Like below? Just use \d+ to search numbers?

[i for i in l if int(re.search('\d+', i).group(0)) > 15]

Demo:

["abcdedf_023.txt", "sdjskdsjd_3131.txt", "dsdsdsrer_044.txt"]

You can also search for _(\d+).txt (use () to catch the numbers like):

[i for i in f if int(re.search('_(\d+).txt', i).group(1)) > 15]

To remove something like "abc122dedf_01.txt" in your file (if you don't want it).


If you only need the last two numbers in the filenames, for example get 03 from 1203:

[i for i in f if int(re.search('\d+', i).group(0)[-2:]) > 15]
Sign up to request clarification or add additional context in comments.

5 Comments

I think I would need to remove underscore '_' before converting the search result to integer?
@user2436428: Nope, I'm using re.search() in my code. So it will keep searching unless it find a integer.
@user2436428: If there's other integers before that _, and you wish you could ignore them, try the second or the third solution.
I am talking about this statement: int(re.search('_(\d+).txt', i).group(0))
@user2436428: Oh, my bad. As you can see I'm using (\d+) to catch the integers, but I forgot change .group(0) to .group(1). I've edited my answer.
2

I would use split

>>> l = ["abcdedf_023.txt",
"foeoioo_011.txt", 
"sdjskdsjd_3131.txt", 
"dsdsdsrer_044.txt", 
"rgfbfgrt_12.txt"]
>>> [i for i in l if int(i.split('.')[0].split('_')[-1]) > 15 ]
['abcdedf_023.txt', 'sdjskdsjd_3131.txt', 'dsdsdsrer_044.txt']

Replace 15 in the above list comprehension with the variable which actually contains the number you want to check with.. Note that the variable must be of type interger or convert it to int during condition checking.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.