I am currently working with python docx and it requires hex values to format font color for example
font.color.rgb = RGBColor(0x70, 0xad, 0x47)
However I need to store the arguement for RGBColor
in a variable, a dictionary to be exact however when you store a hex value in a variable it will format it to an int. example:
code = (0x70, 0xad, 0x47)
print(code)
returns: (112, 173, 71)
and storing it using the hex()
function will format it to be a str
.
code = (hex(0x70), hex(0xad), hex(0x47))
print(code)
returns: ('0x70', '0xad', '0x47')
and the RGBColor
operator will not accept strings, and I cannot re-format these strings back into an int
because I get the error ValueError: invalid literal for int() with base 10: '0x70'
In summery how can I store a hex value such as 0x70, 0xad, 0x47
as an integer that I can then feed into the RGBColor
opperator?
font.color.rgb = RGBColor(112, 173, 71)
produces the same result as:
font.color.rgb = RGBColor(0x70, 0xad, 0x47)
The 0x7f
format is just an alternate Python literal form for an int
value. There is only one kind of int
, just multiple ways of expressing the same value as a literal. See the Python docs on numeric literals for a full breakdown of those options:
https://docs.python.org/3/reference/lexical_analysis.html#numeric-literals
Note that you can also use:
font.color.rgb = RGBColor.from_string("70ad47")
If that is more convenient for you.
https://python-docx.readthedocs.io/en/latest/api/shared.html#docx.shared.RGBColor.from_string