Home > OS >  How do i convert a string list with numbers with commas to an integer list in python
How do i convert a string list with numbers with commas to an integer list in python

Time:09-05

How do i convert this to a list of integer in python?

my code:

lst = input("Kindly input a string")

[int(element) for element in lst]

I keep getting

ValueError: invalid literal for int() with base 10: '['

CodePudding user response:

Assuming you are entering string inputs like:

"[1, 2, 3]"

you may use ast.literal_eval:

import ast
inp = "[1, 2, 3]"
lst = ast.literal_eval(inp)
print(lst)  # [1, 2, 3]

Or, you could use re.findall:

inp = "[1, 2, 3]"
lst = [int(x) for x in re.findall(r'\d ', inp)]
print(lst)  # [1, 2, 3]

CodePudding user response:

You can use python eval:

eval("[1, 2, 3]")
# [1, 2, 3]

eval("2,4,2 ,2 ,23, 23")
# (2, 4, 2, 2, 23, 23)

exact case would be:

lst = eval(input("Kindly input a string"))

CodePudding user response:

By string manipulations: remove the square brackets with str.strip, make a list of numbers by splitting the string at each occurrence of ', ' (here for simplicity it is assumed there is always a white space after the ,) and finally cast each string-number to integer.

s = "[1, 2, 3]"

l = list(map(int, s.strip('][').split(', ')))
print(l)

More complex situation,for example when the presence of the white space is not sure it can be solved with a for-loop approach or with regular expression. For nested list then ast.literal_eval is the choice.

  • Related