Using python to dump hexadecimals into YAML

五迷三道 提交于 2019-12-01 09:03:04

问题


Now I'm dumping into a YAML document. It's working as it should for the most part. When I try to dump a hexadecimal such as "0x2A" it converts to 42. Isn't there any way to maintain it's hexadecimal format? A string won't work sadly. And int( 0x2A, 16) also just gives me a 42.


回答1:


You may be looking for hex(0x2a) == hex(42) == '0x2a'.

Unless you're looking for a way to convince your existing dumping function to use hexadecimal instead of decimal notation...


Answering to your comment below, if the problem is that you want upper case letters for the hexadecimal digits (but lower case for the 0x) then you have to use string formatting. You can choose one of the following:

"0x%02X" % 42                     # the old way
"0x{:02X}".format(42) == "0x2A"   # the new way

In both cases, you'll have to print the 0x explicitly, followed by a hexadecimal number of at least two digits in upper case, left-padded with a zero if your number has only one digit. This is denoted by the format 02X, same as in C's printf.




回答2:


This should do it:

>>> import yaml
>>> class HexInt(int): pass
... 
>>> def representer(dumper, data):
...     return yaml.ScalarNode('tag:yaml.org,2002:int', hex(data))
... 
>>> yaml.add_representer(HexInt, representer)
>>> yaml.dump({"n": HexInt(42)})
'{n: 0x2a}\n'



回答3:


Representing all int in hex format, without a HexInt class, can be done using:

def hexint_presenter(dumper, data):
    return dumper.represent_int(hex(data))
yaml.add_representer(int, hexint_presenter)

With reference to this answer.



来源:https://stackoverflow.com/questions/18666816/using-python-to-dump-hexadecimals-into-yaml

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