Convert True/False value read from file to boolean

前端 未结 14 869

I\'m reading a True - False value from a file and I need to convert it to boolean. Currently it always converts it to True even if the value is set

相关标签:
14条回答
  • 2020-12-07 19:03

    Just to add that if your truth value can vary, for instance if it is an input from different programming languages or from different types, a more robust method would be:

    flag = value in ['True','true',1,'T','t','1'] # this can be as long as you want to support
    

    And a more performant variant would be (set lookup is O(1)):

    TRUTHS = set(['True','true',1,'T','t','1'])
    flag = value in truths
    
    0 讨论(0)
  • 2020-12-07 19:04

    You can do with json.

    In [124]: import json
    
    In [125]: json.loads('false')
    Out[125]: False
    
    In [126]: json.loads('true')
    Out[126]: True
    
    0 讨论(0)
提交回复
热议问题