arrx=list(map(int,input().strip().split(',')))
I am trying the above code to get the input of '[7,5,1,6,3,4]'
but I am getting an error of invalid literal for int() with base 10: '[7'
.
Can anyone suggest to me a way out of it?
arrx=list(map(int,input().strip().split(',')))
I am trying the above code to get the input of '[7,5,1,6,3,4]'
but I am getting an error of invalid literal for int() with base 10: '[7'
.
Can anyone suggest to me a way out of it?
You can use .strip()
to strip them by specifying the characters:
arrx=list(map(int,input().strip('[] ').split(',')))
Note that if your input is in reality a JSON list, you can more robustly parse it as json:
import json
arrx = json.loads(input())
And if it's a Python literal expression, you can use ast
:
import ast
arrx = ast.literal_eval(input())
Save your breath and use literal_eval
:
import ast
a = ast.literal_eval(input())
print(a, len(a), a[0], "and whatever you want")
Use
list comprehension and
re.findall
, which search for \d+
(1 or more digits):
import re
# '[7,5,1,6,3,4]'
arr = [int(i) for i in re.findall(r'\d+', input())]
print(arr)
# [7, 5, 1, 6, 3, 4]
The error you were getting is due to incorrect parsing of the input: you are not removing the brackets: [
and ]
. From the docs .strip()
without arguments means remove the leading and trailing whitespace. And split(',')
splits on comma (BTW, if you have comma with whitespace in the middle of the input string, the whitespace is not removed).