I'm solving a problem and the user will give the input in this pattern-
[5,10,15,20]
Since this is an input given by the user, it is a string. I want to convert these numbers into integer and store them in a list.
I tried using the following code -
import re
mystr=input()
mylist=list(re.split('[ |, |] ',mystr))
print(mylist)
The output is:
['[5,10,15,20]']
Why isn't re.split() splitting that input properly? I want the output to be a list of integers which were entered by the user.
I apologise if the question is a duplicate. I'm a newbie to python as well as to stackoverflow.
Many Thanks.
To convert a string to its python equivalent:
>>> import ast
>>> mystr = '[5,10,15,20]'
>>> x = ast.literal_eval(mystr)
>>> x
[5, 10, 15, 20]
eval
is much more general than ast.literal_eval
. But, ast.literal_eval
is much safer to use.
From the python online docs:
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
Changed in version 3.2: Now allows bytes and set literals.
Let's slightly modify the regex:
>>> mystr = '[5,10,15,20]'
>>> list(re.split('[ |, |]+', mystr))
['[5', '10', '15', '20]']
To get rid of the leading and trailing square brackets:
>>> list(re.split('[ |, |]+', mystr.strip('[]')))
['5', '10', '15', '20']
The above gives us a list of strings. To convert them to integers:
>>> [int(x) for x in re.split('[ |, |]+', mystr.strip('[]'))]
[5, 10, 15, 20]