-1

I have a string field : [42, 42, 42]. I want to convert this field in list format.

For now i have the following function :

def stringToList(string):
    # input format : "[42, 42, 42]" , note the spaces after the commas
    string = string[1:len(string)-1]
    try:
        if len(string) != 0: 
            tempList = string.split(", ")
            newList = list(map(lambda x: str(x), tempList))
        else:
            newList = []
    except:
        newList = [-9999]

    return(newList)

I want to know if there is a simpler or a shorter method to have the same result.

Thank you

Clement Ros
  • 307
  • 3
  • 13

1 Answers1

0

Use ast.literal_eval().

>>> import ast
>>> ast.literal_eval("[42, 42, 42]")
[42, 42, 42]
AKX
  • 93,995
  • 11
  • 81
  • 98
  • Thank for your answer. When i tried to generalise to all my Dataframe i hve the error 'malformed node or string: <_ast.name at="" object="">'. Here is my code corpus["correct_localisation"].apply(lambda x: ast.literal_eval(x)). Do you have an idea ? – Clement Ros Dec 10 '19 at 09:26
  • The string you're attempting to convert contains something else than just numbers (as in your example), then. Based on the error, it's probably something like `[foo, bar, 123]`. – AKX Dec 10 '19 at 09:30
  • I i have value like [Pays-de-Galles, Pays-Bas, Allemagne, Belgique]. ast.literal_eval() still work ? – Clement Ros Dec 10 '19 at 09:34
  • No. It works for strings that would be valid Python syntax. – AKX Dec 10 '19 at 10:04