Python Forum
Help with conversion program
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with conversion program
#1
I have errors in my code, it is for converting RGB to Hex in python.
 def color(RGB):
  if RGB > 255:
    RGB = 255
  elif RGB < 0:
    RGB = 0
    RGB = hex(RGB)[2:].upper()
  if len(RGB)<2:
    RGB = '0'+RGB
  return RGB    
 def rgb(r, g, b):
  return color(r)+color(g)+color(b)
It shows for line 7. the following is thrown:

Error:
TypeError: object of type 'int' has no len()
Does anyone have recommendations to help me fix this program?

I already tried adding str() to len(RGB)<2: with no successes.
Yoriz write Aug-19-2022, 09:01 PM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
Your indentation was wrong on line 6. This was only called if RGB < 0
RGB = hex(RGB)[2:].upper()
Use f'string formatting. It will do the zero fill and upper case for you. In the code below, "02X" Says convert to upper case hexadecimal (X) and pad with 0 (0) to a width of 2 characters (2). I also prefer using min and max for clipping numbers to a range.
def rgb2hex(r, g, b, prefix=""):
    clipped = (max(0, min(255, c)) for c in (r, g, b))
    return prefix + "".join((f"{c:02X}" for c in clipped))

print(rgb2hex(184, 7, 280, "#"))
Output:
#B807FF
uwl likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Lightbulb Help with Tempature Conversion Program booponion 3 1,893 Oct-16-2020, 05:59 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020