Python 中布尔值的字符串比较
String comparison of Boolean value in Python
如果我有像下面这样的 Yaml -
Drives:
Drive: Local
Default: true
Drive: Remote
Default: false
我在 Python 中读到这个以作为字符串进行布尔比较 -
If Env_obj.get(“default”, “false”) != “true”:
Do something
这样好吗?您应该先评估布尔值吗?
第一个问题是您的 YAML 格式似乎无效(您可以通过 this one 等验证程序进行检查)
这是一个使用 Python 中的 PyYAML
库读取 YAML 的解决方案。无需将字符串转换为布尔值,因为这应该已经完成了。
from io import StringIO
import yaml
yaml_data = StringIO("""
---
Drives:
-
Default: true
Drive: Local
-
Default: false
Drive: Remote
""")
d = yaml.load(yaml_data, yaml.Loader)
d
# {'Drives': [{'Default': True, 'Drive': 'Local'}, {'Default': False, 'Drive': 'Remote'}]}
default = d['Drives'][0]['Default']
default, type(default)
# True <class 'bool'>
如果我有像下面这样的 Yaml -
Drives:
Drive: Local
Default: true
Drive: Remote
Default: false
我在 Python 中读到这个以作为字符串进行布尔比较 -
If Env_obj.get(“default”, “false”) != “true”:
Do something
这样好吗?您应该先评估布尔值吗?
第一个问题是您的 YAML 格式似乎无效(您可以通过 this one 等验证程序进行检查)
这是一个使用 Python 中的 PyYAML
库读取 YAML 的解决方案。无需将字符串转换为布尔值,因为这应该已经完成了。
from io import StringIO
import yaml
yaml_data = StringIO("""
---
Drives:
-
Default: true
Drive: Local
-
Default: false
Drive: Remote
""")
d = yaml.load(yaml_data, yaml.Loader)
d
# {'Drives': [{'Default': True, 'Drive': 'Local'}, {'Default': False, 'Drive': 'Remote'}]}
default = d['Drives'][0]['Default']
default, type(default)
# True <class 'bool'>