Skip to content

Instantly share code, notes, and snippets.

@wblondel
Last active March 6, 2016 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wblondel/0915db4db3d387474260 to your computer and use it in GitHub Desktop.
Save wblondel/0915db4db3d387474260 to your computer and use it in GitHub Desktop.
Provided three int values, this will return a valid hex triplet representing a color. If those values are between [0,255], then it will treat those as RGB values and return the color corresponding to those values.
# Provided three int values, this will return a valid hex triplet representing a color.
# If those values are between [0,255], then it will treat those as RGB values and return the color corresponding to those values.
# This uses the preferred method of string formatting, as described in PEP 3101.
# It also uses min() and max to ensure that 0 <= {r,g,b} <= 255.
def main():
# Let's say you get the parameters as string
parameter = "130,132,245"
# You first need to split it into 3 numbers
r, g, b = map(int, parameter.split(","))
stroke = "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
print(stroke)
# Result : #8284f5
def clamp(x):
return max(0, min(x, 255))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment