I need to extract the numbers between 2 delimiters ("_dg" and ".csv") in the list of filenames in file00 using Python 3.11.1. The desired result is:
[‘89603′,’89641’]
Here is my code:
file00 = ['Stats_d2023-07-15_dg89603.csv', 'Stats_d2023-07-15_dg89641.csv']
# getting index of substrings
idx1 = [fn.find("_dg") for fn in file00]
idx2 = [fn.find(".csv") for fn in file00]
dgs = [fn[idx1 + len(fn) + 1: idx2] for fn in file00]
Here is my console output:
>>> file00 = ['Stats_d2023-07-15_dg89603.csv', 'Stats_d2023-07-15_dg89641.csv']
>>>
>>> # getting index of substrings
>>> idx1 = [fn.find("_dg") for fn in file00]
>>> idx2 = [fn.find(".csv") for fn in file00]
>>>
>>> dgs = [fn[idx1 + len(fn) + 1: idx2] for fn in file00]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
TypeError: can only concatenate list (not "int") to list
>>>
I suspect that at least one of my problems is that idx1 and idx2 are themselves lists and I am currently erroneously treating them as scalars.
Any assistance is appreciated.
>Solution :
Correcting your list comprehension this way:
dgs = [fn[fn.find("_dg") + len("_dg") : fn.find(".csv")] for fn in file00]
outputs the required substrings:
['89603', '89641']