-2

How to take numbers if the stdin is of this form: [2,7,11,15]

l = list(map(int, input().split(','))) ; print(l)

input : [2,7,11,15]

ValueError: invalid literal for int() with base 10: '[2'
  • Does this answer your question? [Convert string representation of list to list](https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list) – Ryuzaki L Oct 30 '19 at 17:42

2 Answers2

3

If you split using only the comma, you keep the [ and ]

value.split(',') >> ['[2', '7', '11', '15]']

You can do one of these ways :

  • manually l = list(map(int, value[1:-1].split(',')))

  • using a lib l = ast.literal_eval(value) (import ast)

azro
  • 53,056
  • 7
  • 34
  • 70
0

As others stated, rather use ast.literal_eval or some kind of an own parser. But for the sake of your simple example, you could go for:

somestring = "[2,7,11,15]"

somelist = list(map(int, map(str.strip, somestring.strip("[]").split(","))))
print(somelist)
# [2, 7, 11, 15]
Jan
  • 42,290
  • 8
  • 54
  • 79