Explore

# Convert Hex To RGB In Python

In this tutorial I will show you the python program to convert Hex to RGB color code, Hex is a color code format which uses hexadecimal values to indicate a color whereas RGB is another color code which stands for red, green and blue.

I hope you understood what RGB and Hex are. Now let’s see how to convert a Hex color code to RGB color code in python.

## Python Code To Convert Hex To RGB Color

``````
hex = input('Enter HEX value: ').lstrip('#')
print('RGB value =', tuple(int(hex[i:i+2], 16) for i in (0, 2, 4)))
```
```

Above is the code for converting Hex to RGB, this code uses some python functions so let’s see how this code works:

• The code prompts the user to enter a HEX value using the `input()` function.
• The entered HEX value is stored in the variable `hex`.
• The `lstrip('#')` function is used to remove any leading ‘#’ character from the input, allowing the code to handle both ‘#FFFFFF’ and ‘FFFFFF’ formats.
• The `tuple(int(hex[i:i+2], 16) for i in (0, 2, 4))` expression converts the HEX value to RGB.
• It splits the HEX value into three 2-character segments (representing the red, green, and blue components).
• For each segment, `int(hex[i:i+2], 16)` converts the segment to an integer using base 16 (hexadecimal).
• The resulting RGB values are collected as a tuple.
• Finally, the RGB value is displayed using the `print()` function.

Now you can run this code to run this program you need to have python installed, if you don’t have, then read this: Install and setup python or else use this online python compiler, after running the program, you will see your given Hex code to an RGB Color Code like below.

Output

``````
Enter HEX value: #eeeeee
RGB value = (238, 238, 238)
```
```

As you can see, we have successfully converted Hex Color to RGB color, I hope you found this program helpful, want to know how to convert RGB to Hex color code then read this tutorial: Convert RGB To Hex In Python.

Here are some more python programs you will find helpful:

I hope you found what you were looking for from this python tutorial, and if you want more python tutorials like this, do join our Telegram channel to get updated.

Thanks for reading, have a nice day 🙂