[英]Storing hex values as integers
我目前正在使用 python docx,它需要十六進制值來格式化字體顏色,例如
font.color.rgb = RGBColor(0x70, 0xad, 0x47)
但是,我需要將RGBColor
的參數存儲在一個變量中,確切地說是一個字典,但是當您將一個十六進制值存儲在一個變量中時,它會將其格式化為一個 int。 例子:
code = (0x70, 0xad, 0x47)
print(code)
回報: (112, 173, 71)
並使用hex()
function 存儲它會將其格式化為str
。
code = (hex(0x70), hex(0xad), hex(0x47))
print(code)
回報:( ('0x70', '0xad', '0x47')
並且RGBColor
運算符不接受字符串,我無法將這些字符串重新格式化回int
,因為我收到錯誤ValueError: invalid literal for int() with base 10: '0x70'
在夏季,我如何將0x70, 0xad, 0x47
等十六進制值存儲為 integer,然后我可以將其輸入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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.