converting python list of strings to their type

后端 未结 7 669
旧时难觅i
旧时难觅i 2020-12-05 19:57

given a list of python strings, how can I automatically convert them to their correct type? Meaning, if I have:

[\"hello\", \"3\", \"3.64\", \"-1\"]
<         


        
7条回答
  •  渐次进展
    2020-12-05 20:40

    def tryEval(s):
      try:
        return eval(s, {}, {})
      except:
        return s
    
    map(tryEval, ["hello", "3", "3.64", "-1"])
    

    Only do this if you trust the input. Also, be aware that it supports more than just literals; arithmetic expressions will be evaluated as well.

提交回复
热议问题