Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if a string can be converted to list Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading