Home > other >  how to assign string input as list in python
how to assign string input as list in python

Time:12-06

User is giving list as input [1,2,3,4]:

a = input()

It is taking this as str. I want to get this data into local list b.

b = a.strip('][').split(', ')
print(b)

Output: ['1,2,3,4']

How to get list individually not a single entity?

CodePudding user response:

You should do .split(',') instead of .split(', ')

CodePudding user response:

You can use ast.literal_eval to do so.

import ast

a = input()
b = ast.literal_eval(a)

print(b)

# output
[1, 2, 3, 4]

From the docs:

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, None and Ellipsis.

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.

CodePudding user response:

the problem is that in the line:

b = a.strip('][').split(', ')

you used ', ' with whitespace instead of ',' without whitespace because your input does not have any spaces as shown below:

user is giving list as input [1,2,3,4]

CodePudding user response:

ast.literal_eval(a) gets the string input as a list datatype, which can be converted into a list of individual strings with map:

import ast
b = list(map(str,ast.literal_eval(a)))

['1', '2', '3', '4']

CodePudding user response:

You must split on ',' and if these are all integer values, you can change str to int using list-comprehension:

b = [int(i) for i in a.strip('[]').split(',')]

Output:

[1, 2, 3, 4]
  • Related