How to parse string representations of bool into bool in python?

≡放荡痞女 提交于 2021-02-10 14:26:58

问题


My scenarios where I need it:

  1. User is inputting True or False and it is parsed as str by default. I cannot change the parsing type as python 3+ parses as str (Using Python 3.8) So when I parse bool(input('Enter True or False')), it returns True regardless since default bool function only returns False when there is an empty string. True otherwise.

  2. I have a json for which I need it.

It has following representation:

list_of_visits ='''{"Museum": "True",
"Library": "True",
"Park": "False"}
'''

Note that I cannot have its representation without qoutes as:

list_of_visits ='''{"Museum": True,
"Library": True,
"Park": False}
'''

Cause parsing this as follows throws error:

jsonic = json.loads(list_of_visits)
jsonic

But I need to parse from int and float as well at some places and I cannot write functions for each type separately . I am trying to build a one-stop solution which might inherit functionality from bool() and does this conversion as well and I can use it everywhere i.e. solution which can not only perform traditional bool() operations but also able to parse string representations.

Currently I do following steps:

if type(value) == str and value =='True':
    reprs = True
elif type(value) == str and value =='False':
    reprs = False
else:
    reprs = bool(value)

回答1:


You can define your own function which may work in all scenarios as:

def get_bool(key):
    return value if value := {'True':True, 'False':False}.get(key) else bool(key)
    

For a single value such as input you might parse it as:

get_bool('False')

which returns: False

For jsons like that you might do:

from toolz.dicttoolz import valmap
valmap(get_bool, jsonic)

which returns:

{'Museum': 1, 'Library': 1, 'Park': 0}
    

For 3.7 and lower:

I'm in love with walrus operator since it came out in python 3.8. Anyone looking for lower versions might need some repetitions:

def get_bool(key):
return {'True':True, 'False':False}.get(key) if  key.title() in {'True':True, 'False':False}.keys() else bool(key)

Note that though it does work for every case, your JSON representation is wrong. JSONs can have boolean values so can the string representations of JSONs. But you got to use javascript syntax as true and false instead of Python's True & False. Since JSON is a javascript notation.



来源:https://stackoverflow.com/questions/64380912/how-to-parse-string-representations-of-bool-into-bool-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!