0

While writing a few unit tests, I had to convert RGB colors to HEX. My function for the conversion is

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

The output that I am getting using the unit test function (Selenium using Python ) is in the format rgba(255, 255, 255, 1).

Passing this in the rgb_to_hex() [ without the rgba] gives me this error :

ValueError: invalid literal for int() with base 10: '(255, 255, 255, 1)'

I read this link, which makes me think the space between the values is the reason for this. However, I'm not able to resolve this. How to get past this?

Community
  • 1
  • 1
demouser123
  • 4,108
  • 9
  • 50
  • 82

1 Answers1

0

There may be many reasons : 1. rgb should be tuple in this case having 3 values. So (255, 255, 255) in form of tuple needs to be passed here instead of (255, 255, 255, 1) 2. rgb has to be a tuple, if it is string this will not work.

Try using following commands in python interpreter

"#%02x%02x%02x" % (255, 255, 255)

it will give the expected result "#ffffff"

if we run the following

 "#%02x%02x%02x" % (255, 255, 255,1)

it will say not all arguments converted during string formatting.

But from stacktrace shown in the question looks like you are passing '(255, 255, 255, 1)' as single string, which obviously can not be parsed to an it. So make sure you are converting "(255, 255, 255, 1)" string into a tuple (255, 255, 255) before passing it to the formatter. you can use split function on string to parse it and then create a tuple from the splitted value. remember to clip off brackets from the splitted strings.

e.g

def rgb_to_hex(rgb): #for example if rgb = "(255, 255, 255, 1)"

new_string = rgb[1:-4]  # remove starting brace and , 1) from last
# new_strings will be "255, 255, 255"

string_fractions = input_string.split(",")
# string fractions will be ['255', ' 255', ' 255']

# now notice it is list of strings and we need a tuple of ints
int_tuples = tuple(map(int, input_string.split(",")))
# int_tuples will be (255, 255, 255)

return '#%02x%02x%02x' % int_tuples
Satish Gupta
  • 1,447
  • 1
  • 12
  • 14