1

how can I check if the directory name is a year using python ? If I have directories called 2018, 2019, 2020, test1, test2, I want to get only directories which name is a year . in this case I want directories with name : 2018, 2019, 2020

Jan
  • 42,290
  • 8
  • 54
  • 79
Nada Essam
  • 41
  • 1
  • 5
  • Does this answer your question? [python check if year is in string](https://stackoverflow.com/questions/33930527/python-check-if-year-is-in-string) – TheZadok42 Apr 07 '20 at 16:53
  • Have you tried regular expressions? Let's consider you only want years from 0 to 9999, then this ```result = re.match(r'\d{4}$', my_string)``` matches exactly that. You can extrapolate from this to match your exact need. – Vaduva Mihaita Bogdan Apr 07 '20 at 16:56

1 Answers1

0

You might get along with a regular expression:

^[12]\d{3}$

See a demo on regex101.com.


Or with the help of some programming logic:
import re

folders = ["2018", "2019", "2020", "test1", "200000000", "test2   djdsdjk"]

rx = re.compile(r'^\d+$')

filtered = [folder
            for folder in (int(item) for item in folders if rx.match(item))
            if 1900 <= folder <= 2100]
print(filtered)

This yields

[2018, 2019, 2020]
Jan
  • 42,290
  • 8
  • 54
  • 79