Explore

Close
Python Programs Share

Convert RGB To Hex In Python

Convert RGB To Hex In Python

Looking for a way to convert RGB to Hex in python then you are at the right place, today in this python tutorial I will show you the python program to convert rgb to hex color code so follow me till the end.

RGB is a color code which stands for red, green and blue. They each have a unique value like this (255,255,255) which results in white color.

Hex is another color code format which uses hexadecimal values to indicate a color, for example #fffff will result in white color.

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

Python Code To Convert RGB To Hex 


def rgb_to_hex(rgb):
    return '#%02x%02x%02x' % rgb
    
print(rgb_to_hex((255, 255, 255)))

Above is the python program to convert RGB to Hex. You can run this code and see the result. To run this program you need to have python installed, if you don’t have, then read this: Install and setup python.

Follow this steps to run this program:

  • First, create a new folder for this program.
  • Open it in a code editor of your choice.
  • Create a python file with .py extension.
  • Copy and paste the above code in the file.
  • Open a command prompt at the program folder.
  • To run, use this command, python filename.py.

Follow all the above steps if you don’t know how to run a python program. You can also run this program by using this online python compiler. After running the program you will see RGB color code to Hex color code like below

Output


#ffffff

As you can see, we have successfully converted RGB Color to Hex in python. I hope you ran this program successfully.

Want to know how to convert Hex to RGB color code then read this tutorial: Convert Hex To RGB In Python.

Summary

This was the tutorial on converting RGB to Hex in python. I hope you found this tutorial helpful and useful. Do share this tutorial with your friends who might need this or find it helpful.

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 🙂