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

Time:02-15

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:

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.

Apologies for not abiding by the 'how to ask' - I hope this clears it up. Otherwise I will remove the post.

CodePudding user response:

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

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

output:

>> [100, 123, 1456, 9845]
  • Related