converting python list of strings to their type

后端 未结 7 662
旧时难觅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:24

    If the you are truly interested in only strings, floats, and ints, I prefer the more verbose, less-evalful

    def interpret_constant(c):
        try:
            if str(int(c)) == c: return int(c)
        except ValueError:
            pass
        try:
            if str(float(c)) == c: return float(c)
        except ValueError:
            return c
    
    test_list = ["hello", "3", "3.64", "-1"]
    
    typed_list = [interpret_constant(x) for x in test_list]
    print typed_list
    print [type(x) for x in typed_list]
    

提交回复
热议问题