Malformed String ValueError ast.literal_eval() with String representation of Tuple

前端 未结 4 1357
自闭症患者
自闭症患者 2020-11-29 04:00

I\'m trying to read in a string representation of a Tuple from a file, and add the tuple to a list. Here\'s the relevant code.

raw_data = userfile.read().spl         


        
4条回答
  •  心在旅途
    2020-11-29 04:39

    I know this is an old question, but I think found a very simple answer, in case anybody needs it.

    If you put string quotes inside your string ("'hello'"), ast_literaleval() will understand it perfectly.

    You can use a simple function:

        def doubleStringify(a):
            b = "\'" + a + "\'"
            return b
    

    Or probably more suitable for this example:

        def perfectEval(anonstring):
            try:
                ev = ast.literal_eval(anonstring)
                return ev
            except ValueError:
                corrected = "\'" + anonstring + "\'"
                ev = ast.literal_eval(corrected)
                return ev
    

提交回复
热议问题