1
def colour():
        c = np.random.uniform(0, 1) 
        c1 = np.random.uniform(0, 1)
        c2 = np.random.uniform(0, 1)
        r = hex(int(c*255))[2:]
        g = hex(int(c1*255))[2:]
        b = hex(int(c2*255))[2:]
        return "#" + r + g + b
    code = colour()
    print(code)
    dis = HTML(r'<h3 style="color:{code};">This is the colour you feel like today. Like it? </h3>')
    display(dis)

I randomly generate three colors and i want to print my sentence three time with colors generated above.I want to make a list and put three color's string form in it, then use for loop to output my answer.

Hope I explain my question cleary, and if there are any problem, i will give another explanation, thank you!

  • 1
    Does this answer your question? [Is there a Python equivalent to Ruby's string interpolation?](https://stackoverflow.com/questions/4450592/is-there-a-python-equivalent-to-rubys-string-interpolation) – L.Grozinger May 26 '21 at 11:13

2 Answers2

0

Yeah, definitely. Try this:

mylist = [colour() for i in range(3)]

and then

for code in mylist:
    print(code)
    dis = HTML(r'<h3 style="color:{code};">This is the colour you feel like today. Like it? </h3>')
    display(dis)
Captain Trojan
  • 2,800
  • 1
  • 11
  • 28
0

Your code should work with f-strings. Replace the r'...' with f'...'.

dis = HTML(f'<h3 style="color:{code};">This is the colour you feel like today. Like it? </h3>'

See https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings or https://realpython.com/python-f-strings/ for reference.

schilli
  • 1,700
  • 1
  • 9
  • 17