简体   繁体   中英

How can I generate a random hex color code using python?

I am working on a Discord bot in python, and I need a way to generate a random hex color code, I looked it up online and I found this:

import random
color = "%06x" % random.randint(0, 0xFFFFFF)

Is it possible to do the same thing using an f-string?

import random
color = f"{"%06x" % random.randint(0, 0xFFFFFF)}"

Is this what you want?

However, I don't think this is a good way to create a hex code. Personally, I would do it like this:

import random
random_number = random.randint(0,16777215)
hex_number = str(hex(random_number))
hex_number ='#'+ hex_number[2:]

But that's just a preferance!

Yes, you can use:

import random

color = f'{"%06x" % random.randint(0, 0xFFFFFF)}'

Let me know if this is what you are trying to achieve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM