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'
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'
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
)
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]