0

Challenge

How do I get from (255, 255, 255, 0) to '(255, 255, 255, 0)' when the former is a tuple?

Details:

I'm converting hex colors to rgba colors using an approach described here. I'm doing this to use the color as arguments with an opacity element like so:

color = 'rgba(255, 255, 255, 0)'

As you might already have guessed, the argument has to be of a string type. And I've come so far as having the integers in a tuple like so

(255, 255, 255, 0)

Now I need to enclose the whole tuple in a string like '(255, 255, 255, 0)' to get to my last step:

'rgba(255, 255, 255, 0)'

I'm afraid I'm missing some obvious and very fundamental element of Python here, but any suggestions would be great!

vestland
  • 55,229
  • 37
  • 187
  • 305

4 Answers4

6

I am afraid there's no simple conversion function for that, however, this should work:

t = (255, 255, 255, 0)
f'rgba({t[0]}, {t[1]}, {t[2]}, {t[3]})'

Even shorter:

t = (255, 255, 255, 0)
f'rgba{str(t)}'

Depending on the context, I would probably prefer the first option for two reasons:

  1. second option, while shorter, depends on the str implementation for tuples. It is unlikely to change, but unlikely does not mean impossible
  2. (the most important) it just accidentally occurred that str view for tuples fits the expected string pattern. Once string pattern changes it may be a nightmare bug to trace and fix.

The first option explicitly separates representation from data, and also allows us to use any iterable, not only tuples. And using a class instead of the tuple, in this case, may be a very robust idea.

Alexander Pushkarev
  • 1,075
  • 6
  • 19
3

How about casting it in str?

>>> color = (255, 255, 255, 0)
>>> str(color)
'(255, 255, 255, 0)'
>>> str_color = 'rgba' + str(color)
>>> str_color
'rgba(255, 255, 255, 0)'
Jake Tae
  • 1,681
  • 1
  • 8
  • 11
3

You should be able to use string formatting and tuple unpacking for this:

your_tuple = (255, 255, 255, 0)
'rgba({}, {}, {}, {})'.format(*your_tuple)
Andrew
  • 1,072
  • 1
  • 7
  • 15
2

Simply str((255, 255, 255, 0))

>>> a = (255, 255, 255, 0)
>>> type(a)
<class 'tuple'>
>>> b = str(a)
>>> print(b, type(b))
(255, 255, 255, 0) <class 'str'>
Sid
  • 2,174
  • 1
  • 13
  • 29