easy +10 pts

Validate Hex Color Code

Check if a string is a valid 3 or 6-digit hexadecimal color code with optional #.

Write a function `is_valid_hex_color(s: str) -> bool` that returns `True` if the input string `s` is a valid hex color code, and `False` otherwise. A valid hex color code must: - Optionally start with a single `#` character. - Contain either exactly 3 or exactly 6 hexadecimal digits (0-9, a-f, A-F). - Have no other characters, no spaces, and no extra `#`. The function should be case-insensitive regarding the hex digits. Examples: - `"#ABC"` and `"#abc"` are valid. - `"#A1B2C3"` and `"#a1b2c3"` are valid. - `"123456"` and `"FFF"` are valid (without #). - `"#ABCD"` (4 digits), `"#12"`, `"#12 345"`, `"##123"`, and `"#GGG"` are invalid. Implement the function using a regular expression.

Constraints

Input string length will be between 0 and 20. Use `re.fullmatch` or anchor the pattern to match the entire string.

Example

>>> is_valid_hex_color('#A1B2C3')
True
>>> is_valid_hex_color('ABC')
True
>>> is_valid_hex_color('123456')
True
>>> is_valid_hex_color('#ABCD')
False
>>> is_valid_hex_color('')
False
10 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use the `re.fullmatch()` function to ensure the entire string matches.
The pattern should allow an optional `#` at the start: `#?`.
For hex digits, use `[0-9a-fA-F]` with `{3}` or `{6}`.
Combine the 3 and 6 digit alternatives with `|` and group them.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.