Extract first four digits from string within an list

I have a list of folder names. Some names contain numbers only and others have the numbers prefixed before some text.

Where the folder name contains both numbers and text, i would like to extract only the numbers (first four digits).

internal_list = [f.name for f in os.scandir(internal_path) if f.is_dir() ]
print(internal_list)

internal_list shows a list as follows

[1001 Support, 1021 Training, 1022, 1023, 1033 Procedures]

I would like internal_digits to show:

[1001, 1021, 1022, 1023, 1033] 

internal_digits = []
for filename in internal_list:
    if filename in '0123456789':
        internal_digits.append(filename[0:4])
print (internal_digits)

Answer

internal_digits=[i.split()[0] for i in internal_list]

Leave a Reply

Your email address will not be published. Required fields are marked *