将十六进制值存储为整数

Storing hex values as integers

我目前正在使用 python docx,它需要十六进制值来格式化字体颜色,例如

font.color.rgb = RGBColor(0x70, 0xad, 0x47)

但是我需要将 RGBColor 的参数存储在一个变量中,确切地说是一个字典,但是当您将一个十六进制值存储在一个变量中时,它会将其格式化为一个 int。示例:

code = (0x70, 0xad, 0x47)

print(code)

returns: (112, 173, 71)

并使用 hex() 函数存储它会将其格式化为 str.

code = (hex(0x70), hex(0xad), hex(0x47))

print(code)

returns: ('0x70', '0xad', '0x47')

RGBColor 运算符不接受字符串,我无法将这些字符串重新格式化回 int,因为我收到错误 ValueError: invalid literal for int() with base 10: '0x70'

在夏季,如何将 0x70, 0xad, 0x47 等十六进制值存储为整数,然后我可以将其输入 RGBColor 运算符?

font.color.rgb = RGBColor(112, 173, 71)

产生与以下相同的结果:

font.color.rgb = RGBColor(0x70, 0xad, 0x47)

0x7f 格式只是 int 值的另一种 Python 文字形式。 int只有一种,只是同一个值的多种表达方式。有关这些选项的完整细分,请参阅有关数字文字的 Python 文档: https://docs.python.org/3/reference/lexical_analysis.html#numeric-literals

请注意,您还可以使用:

font.color.rgb = RGBColor.from_string("70ad47")

如果这样对你更方便。
https://python-docx.readthedocs.io/en/latest/api/shared.html#docx.shared.RGBColor.from_string