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

Convert a string type object into a list of integer values that can be looped through

Take for example a string such as this:

"[(337680), (333205), (312572), (etc)]"

How could I go about converting this into a list of integer values that can then be looped through?

End result would be something like:

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

[337680, 333205, 315572, etc]

where if I print(my_list[1]) it would return 333205

Some context into what I have been attempting to do in order to resolve this and justification for why I would like to have an answer to this question:

I have compiled a list of several thousand integer values I will be attempting to loop through for the purpose of web scraping a domain. This was accomplished fetching the values from a sql database using psycopg2.
The results return as [(337680,), (333205,), (312572,), (etc,)]. I have already declared the values as int within the sql select command.

I then attempted to use re to remove the commas

clean_values = re.sub(r',(?=\))', '', str(values))

which returned the aforementioned string [(337680), (333205), (312572), (etc)]

To my limited knowledge, selenium (which I am using as scrape tool) requires a string type object for the purpose of executing a search. At least, that is how I have been able to run it.

for page in values:
        page = "https://mywebsite/"+str(values)
        driver.get(page)

Unless I convert the aforementioned string to an integer list, when I attempt to execute a search it will error out as it will include the commas, parentheses and quotation marks around the int value I want to use.

>Solution :

numstr = '(100),(123),(1456),(9845)'

l = [int(num.strip('()')) for num in numstr.split(',')]
print(l)

output:

>> [100, 123, 1456, 9845]
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