问题
My scenarios where I need it:
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 returnsTrue
regardless since default bool function only returnsFalse
when there is an empty string.True
otherwise.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