Home > Enterprise >  How can i convert string to int list with python?
How can i convert string to int list with python?

Time:01-18

stringIds = "948274432, 948364892, 943224012"

I have such a string. How can I transfer the ids here into a list by converting them to int?

intList = []
for x in stringIds:
    intList.append(int(x))

I tried a code like this but the error I got ValueError: invalid literal for int() with base 10: ','

Here is the sample list I want to get

intList = [948274432, 948364892, 943224012]

CodePudding user response:

str.split can split the string at the commas, then you can apply int to each element to get them as numbers.

intList = [int(x) for x in stringIds.split(', ')]

or, written out as a for loop like in your example,

intList = []
for x in stringIds.split(', '):
    intList.append(int(x))

CodePudding user response:

You can convert a string of comma-separated integers to a list of integers in Python by first splitting the string on the commas, then iterating over the resulting list and converting each element to an integer. Here's an example:

    stringIds = "948274432, 948364892, 943224012"
intList = [int(x) for x in stringIds.split(",")]

This uses a list comprehension to iterate over the elements of the list returned by stringIds.split(",") and converts each element to an integer using the int() function. The resulting list comprehension creates a new list with the integers.

Another way of doing this is using the map() function:

stringIds = "948274432, 948364892, 943224012"
intList = list(map(int,stringIds.split(",")))

This uses the map() function to apply the int() function to each element of the list returned by stringIds.split(",") and then creates a new list with the output of the map.

Your code didn't work because of the for loop, as you were iterating over each character of the string and not over the splitted parts of the string.

  • Related