Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – String Manipulation in List Comprehension

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading