Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/docx/shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
12 changes: 12 additions & 0 deletions tests/test_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down