现在我正在转储到 YAML 文档中.它在大多数情况下都在正常工作.当我尝试转储诸如0x2A"之类的十六进制时,它会转换为 42.有没有办法保持它的十六进制格式?可悲的是,字符串不会起作用.而 int(0x2A, 16) 也只是给了我一个 42.
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.
您可能正在寻找 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...
回答您在下面的评论,如果问题是您想要十六进制数字的大写字母(但 0x 的小写字母),那么您必须使用字符串格式.您可以选择以下选项之一:
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
在这两种情况下,您都必须显式打印 0x,后跟至少两位大写的十六进制数字,如果您的数字只有一位,则左填充零数字.这由 02X 格式表示,与 C 的 printf 中的格式相同.
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.
这篇关于使用 python 将十六进制转储到 YAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
python:不同包下同名的两个模块和类python: Two modules and classes with the same name under different packages(python:不同包下同名的两个模块和类)
配置 Python 以使用站点包的其他位置Configuring Python to use additional locations for site-packages(配置 Python 以使用站点包的其他位置)
如何在不重复导入顶级名称的情况下构造python包How to structure python packages without repeating top level name for import(如何在不重复导入顶级名称的情况下构造python包)
在 OpenShift 上安装 python 包Install python packages on OpenShift(在 OpenShift 上安装 python 包)
如何刷新 sys.path?How to refresh sys.path?(如何刷新 sys.path?)
分发带有已编译动态共享库的 Python 包Distribute a Python package with a compiled dynamic shared library(分发带有已编译动态共享库的 Python 包)