Home > other >  Check if a string can be converted to list Python
Check if a string can be converted to list Python

Time:10-10

I need to check if a string like foo = "[1,2,3]" can be converted to a list foo = [1,2,3] but the problem is sometimes foo = "[1,2,3]." or foo = "[1,2,3" or foo = "[test]" # it should be "['test']" to get accepted ...etc.

My approach to solving this:

if isinstance(literal_eval(foo), list): # if its literal_eval is a list
    foo = literal_eval(foo) # then make it a list

so when I use isinstance(literal_eval(foo), list) it raises error if foo was something like foo = "[1,2,3]." instead of returning a bool True or False.

Is there any possible way to check if my string can be a list before actually converting it to a list?

CodePudding user response:

Use a try/except block:

import ast
def check(foo):
    try:
        return isinstance(ast.literal_eval(foo), list)
    except SyntaxError:
        return False

check('[1,2,3].')
# False

check('1')
# False

check('[1, 2]')
# True
  • Related