From a5b34a82def54532e97a12b284450b39991dddc8 Mon Sep 17 00:00:00 2001 From: Miro <200482516+Mirochill@users.noreply.github.com> Date: Mon, 25 May 2026 20:51:27 +0200 Subject: [PATCH] Support RGBColor shorthand hex strings --- src/docx/shared.py | 7 ++++++- tests/test_shared.py | 12 ++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/docx/shared.py b/src/docx/shared.py index 6c12dc91e..21313f868 100644 --- a/src/docx/shared.py +++ b/src/docx/shared.py @@ -142,7 +142,12 @@ def __str__(self): @classmethod def from_string(cls, rgb_hex_str: str) -> RGBColor: - """Return a new instance from an RGB color hex string like ``'3C2F80'``.""" + """Return a new instance from an RGB color hex string. + + Supports six-digit values like ``'3C2F80'`` and three-digit shorthand like ``'F00'``. + """ + if len(rgb_hex_str) == 3: + rgb_hex_str = "".join(char * 2 for char in rgb_hex_str) r = int(rgb_hex_str[:2], 16) g = int(rgb_hex_str[2:4], 16) b = int(rgb_hex_str[4:], 16) diff --git a/tests/test_shared.py b/tests/test_shared.py index fb6c273cb..cc4de7170 100644 --- a/tests/test_shared.py +++ b/tests/test_shared.py @@ -113,6 +113,18 @@ def it_can_construct_from_a_hex_string_rgb_value(self): rgb = RGBColor.from_string("123456") assert rgb == RGBColor(0x12, 0x34, 0x56) + @pytest.mark.parametrize( + ("rgb_hex_str", "expected_rgb"), + [ + ("123", RGBColor(0x11, 0x22, 0x33)), + ("aBc", RGBColor(0xAA, 0xBB, 0xCC)), + ], + ) + def it_can_construct_from_a_three_digit_hex_string_rgb_value( + self, rgb_hex_str: str, expected_rgb: RGBColor + ): + assert RGBColor.from_string(rgb_hex_str) == expected_rgb + def it_can_provide_a_hex_string_rgb_value(self): assert str(RGBColor(0xF3, 0x8A, 0x56)) == "F38A56"