Python Forum
Help with conversion program
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with conversion program
#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


Messages In This Thread
Help with conversion program - by uwl - Aug-19-2022, 08:36 PM
RE: Help with conversion program - by deanhystad - Aug-19-2022, 09:08 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Lightbulb Help with Tempature Conversion Program booponion 3 1,972 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