To convert hex to RGB in Python, validate the CSS hexadecimal token, expand any shorthand, and parse each channel pair in base 16 to produce red, green, and blue integers from 0 to 255.
A CSS color may also contain an alpha byte. Python can return three channel integers for an opaque token or four for a translucent token, but it should preserve CSS's red-green-blue-alpha order and reject malformed values rather than guess.

How CSS hex notation maps to RGB
Each two-digit CSS component is a hexadecimal byte. The digits 0 through 9 and letters A through F are base-16 characters, and each completed pair maps to an integer from 0 through 255. The leading hash marks the value as hexadecimal.
| CSS form | Expansion | Parsed components | Alpha treatment |
|---|---|---|---|
| #RGB | Duplicate each digit | Red, green, blue | Not specified; the preview is opaque |
| #RGBA | Duplicate each digit | Red, green, blue, alpha | Alpha is the final byte |
| #RRGGBB | No expansion needed | Red, green, blue | Not specified; the preview is opaque |
| #RRGGBBAA | No expansion needed | Red, green, blue, alpha | Alpha is the final byte |
Shorthand duplicates each digit, so its one-digit components become full bytes before conversion. In CSS, alpha is always last: the pairs in #RRGGBBAA mean red, green, blue, then alpha. Do not apply color-design conventions that put opacity first. The W3C CSS Color Level 4 hexadecimal notation and MDN's hex-color reference document these rules.
Convert hex to RGB in Python
- Trim the complete input. Remove ordinary whitespace surrounding the token with strip(), but leave whitespace inside the value visible for validation.
- Require the hash and a valid length. The characters after the hash must contain exactly 3, 4, 6, or 8 hexadecimal digits.
- Reject non-hex characters. Check every character against digits 0 through 9 and letters A through F in either case.
- Expand shorthand. For three- and four-digit forms, duplicate each digit to turn each nibble into a complete byte.
- Parse the channel pairs. Pass each two-character pair to Python's int() with base 16.
- Return the appropriate tuple. Return three integers for #RGB and #RRGGBB, or four integers for the forms that contain alpha.
Complete function:
def hex_to_rgb(hex_color):
value = hex_color.strip()
if not value.startswith("#"):
raise ValueError("Hex color must start with #")
digits = value[1:]
if len(digits) not in (3, 4, 6, 8):
raise ValueError("Use 3, 4, 6, or 8 hexadecimal digits")
if any(char not in "0123456789abcdefABCDEF" for char in digits):
raise ValueError("Color contains a non-hexadecimal character")
if len(digits) in (3, 4):
digits = "".join(char * 2 for char in digits)
channels = [int(digits[i:i + 2], 16) for i in range(0, len(digits), 2)]
return tuple(channels)
The function uses only Python built-ins. A concrete call extracts the three color channels and leaves alpha unset when the source does not provide it:
channels = hex_to_rgb("#123")
r, g, b = channels[:3]
alpha_byte = channels[3] if len(channels) == 4 else None
For #123, shorthand expansion produces #112233, and parsing the pairs in base 16 gives red 17, green 34, and blue 51, so the returned tuple is (17, 34, 51).
The function returns raw channel bytes. It does not silently convert an absent alpha into a decimal opacity or change the channel order. For CSS-style opacity, divide the fourth byte by 255.
Choose the output your application needs
A successful parse can produce several useful forms, but they are not interchangeable. Choose based on what the destination accepts and whether the original alpha byte must remain exact.
| Output | Shape | Best fit | Precision note |
|---|---|---|---|
| Python RGB tuple | Three integer bytes | Code expecting red, green, and blue | Contains no alpha member |
| Python RGBA tuple | Three color bytes plus an alpha byte | Code explicitly supporting RGBA | Alpha remains an integer from 0 to 255 |
| CSS rgb() or rgba() | Stylesheet-ready text | Web styles and CSS values | Decimal alpha is rounded for display |
| Normalized HEX | Expanded lowercase CSS token | Exact handoff or round trip | Preserves the alpha byte exactly |
Use individual channel values for an API, canvas operation, image editor, test fixture, or design token. Use CSS output in styles that accept rgb() or rgba(). Keep normalized HEX for exact round trips, especially when alpha cannot be represented cleanly by a short decimal.
To build a readable CSS string from the returned tuple:
def channels_to_css(channels):
r, g, b = channels[:3]
if len(channels) == 4:
alpha_text = f"{channels[3] / 255:.3f}".rstrip("0").rstrip(".")
return f"rgba({r}, {g}, {b}, {alpha_text})"
return f"rgb({r}, {g}, {b})"
This helper displays alpha with up to three decimal places and removes trailing zeros. It does not replace the exact byte in the tuple, so retain that tuple or the normalized HEX when precision matters.
Reject malformed color tokens
Strict validation prevents a typo from turning into a plausible but wrong color. The parser intentionally accepts only the four CSS hexadecimal forms, after trimming ordinary whitespace around the complete token.
- A value without its leading hash is rejected.
- Any digit count other than 3, 4, 6, or 8 is rejected.
- A doubled hash is rejected instead of being silently corrected.
- Whitespace inside the token is rejected.
- Characters outside the hexadecimal alphabet are rejected.
Uppercase and lowercase letters are equivalent. The converter does not parse named colors such as rebeccapurple, hsl(), lab(), lch(), color(), system colors, CSS variables, gradients, or comma-separated palettes. It also does not convert between color spaces, so an input intended for another color model should not be passed as CSS hexadecimal notation.
Check the conversion in your browser
When a Python result needs a second check, paste the same token into the HEX to RGB Converter. It displays the normalized token, CSS output, individual bytes, and a visual result together without uploading the color string to Lizely.
- Paste the CSS color. Enter a value beginning with # in three-, four-, six-, or eight-digit form.
- Read every representation. Check the expanded lowercase HEX, the CSS rgb() or rgba() string, and the individual channel values against the Python output.
- Inspect the preview. Use it as a quick check for an obvious channel-order mistake. For translucent colors, retain the exact alpha byte or normalized eight-digit HEX when round-trip precision matters.
Parsing, formatting, validation, and preview rendering happen locally in the current browser. Three- and six-digit colors are treated as fully opaque for the preview, while four- and eight-digit colors include transparency. Invalid or empty input replaces the previous conversion with a clear error instead of leaving a stale successful result visible.
Apply the result without changing its meaning
Before inserting RGB values into code, confirm whether the destination expects three channels, four channels, or a CSS string. An API that accepts integer RGB should receive the raw byte values directly. If it expects an alpha value from 0 through 1, perform that conversion deliberately rather than copying a CSS-style decimal into an API that interprets it differently.
Hexadecimal CSS colors represent sRGB channel values, not Pantone colors, CMYK ink recipes, or physical measurements. If the next task is checking text readability, use the Color Contrast Checker. For a basic process-color estimate, use the RGB to CMYK Converter, while remembering that dependable print production still requires a managed profile and proofing workflow.
The live preview is a visual sanity check, not a color-management reference. Display brightness, browser profiles, ambient light, and wide-gamut workflows can make the same numeric sRGB color appear different on different screens. For data exchange, rely on the channel values or exact source token rather than judging equivalence from the preview.
If you're weighing options, RGB to CMYK Accuracy: A Practical Browser Guide covers this in detail.
If you're weighing options, How to Avoid RGB to HEX Mistakes Before You Copy covers this in detail.