Suggestion for the RGB to HEX project


I finished the project and it behaves OK I guess, with one exception.

I did not receive any errors. However, when I will choose a RGB value which has red = 0, I will not get the first two digits of the hexadecimal code:

For example:

Cyan has the RGB value (0,255,255)
The hexadecimal value printed by the program should be #00FFFF.

Unfortunately, the printed value is actually FFFF , without the double 0s in the beginning.

def rgb_hex():
  invalid_msg = "The wrong value was inserted"
  red = int(raw_input("Enter the Red (R) value: "))
  if red < 0 or red > 255:
    print invalid_msg
  green = int(raw_input("Enter the Green (G) value: "))
  if green < 0 or green > 255:
    print invalid_msg
  blue = int(raw_input("Enter the Blue (B) value: "))
  if blue < 0 or blue > 255:
    print invalid_msg
  val = (red << 16) + (green << 8) + blue
  print "%s" % (hex(val)[2:]).upper()
def hex_rgb():
  hex_val = raw_input("Enter the color (six hexadecimal digits): ")
  if len(hex_val) != 6 :
    print "Invalid hexidecimal value. Try again."
    hex_val = int(hex_val, 16)
  two_hex_digits = 2 ** 8
  blue = hex_val % two_hex_digits
  hex_val = hex_val >> 8
  green = hex_val % two_hex_digits
  hex_val = hex_val >> 8
  red = hex_val % two_hex_digits
  print "Red: %s Green: %s Blue: %s" % (red, green, blue)
def convert():
  while True:
    option = raw_input("Enter 1 to convert RGB to HEX. Enter 2 to convert HEX to RGB. Enter X to Exit: ")
    if option == '1':
      print "RGB to Hex..."
    elif option == '2':
      print "Hex to RGB..."
    elif option =='X':
      print "Error."


To the code above, I would add the following validation rule:

  if red == 0:
    print "#" + "00" + "%s" % (hex(val)[2:]).upper()
    print "#" + "%s" % (hex(val)[2:]).upper()

Do you think there is a better or a more refined way to achieve this? Do you think that this might have a negative impact?


Hi @bpaulalex ,

Replace this ...

    print "%s" % (hex(val)[2:]).upper()

... with this ...

    print '#{:06X}'.format(val)


Thanks a lot.

Cool stuff.

Do you happen to have a link or something, where this kind of formatting is described?

I wanna know how I can apply this further.


Following are some links to information about the Python str.format() method ...

As you work with formatting output, take into account that ...

  • In Python 2, print is a command, for which the expressions that specify the output are not enclosed in parentheses.
  • In Python 3, print is a function, and the expressions that specify the output must be enclosed in parentheses.

Examples ...

Python 2

import math
print "The value of pi is about {:0.10f}".format(math.pi)

Python 3

import math
print("The value of pi is about {:0.10f}".format(math.pi))

Output, in both cases ...

The value of pi is about 3.1415926536


Thanks a lot for the information. Good stuff.

This can be closed.