Force YAML values to be strings

浪尽此生 提交于 2021-02-08 14:32:34

问题


Look at this code, under Python 2.7:

>>> import yaml
>>> yaml.load('string: 01')
{'string': 1}
>>> :(

Is it possible to obtain the string 01 without modifying the yaml file? I didn't find anything in the docs.


回答1:


Try:

>> import yaml
>> yaml.load('string: 01', Loader=yaml.loader.BaseLoader)
{u'string': u'01'}



回答2:


I was seeking for exactly the opposite effect: Numbers where being converted to stings, but numbers where wanted. I was using accidentally the BaseLoader (Dame copy-paste!).

The LOADER is the answer, as already stated by @Konrad Hałas.

Force Strings:

yaml.load('string: 01', Loader=yaml.loader.BaseLoader)

Force Number: (Default)

yaml.load('string: 01', Loader=yaml.loader.SafeLoader)

Link about Deprecation and detail:

https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation



来源:https://stackoverflow.com/questions/12012774/force-yaml-values-to-be-strings

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