Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is an rgb hex string

I am trying to create a way to proofread command console input and check to make sure that the string is an rgb hex string. (Ex: #FAF0E6) Currently I am working with a try: except: block.

def isbgcolor(bgcolor):
    #checks to see if bgcolor is binary
    try:
        float(bgcolor)
        return True
    except ValueError:
        return False

I tried also using a .startswith('#'). I have seen examples of how to write this function in Java but I'm still a beginner and Python's all I know. Help?

like image 940
user2998514 Avatar asked Nov 23 '25 12:11

user2998514


1 Answers

Normally, the best way to see if a string matches some simple format is to actually try to parse it. (Especially if you're only checking so you can then parse it if valid, or print an error if not.) So, let's do that.

The standard library is full of all kinds of useful things, so it's always worth searching. If you want to parse a hex string, the first thing that comes up is binascii.unhexlify. We want to unhexlify everything after the first # character. So:

import binascii

def parse_bgcolor(bgcolor):
    if not bgcolor.startswith('#'):
        raise ValueError('A bgcolor must start with a "#"')
    return binascii.unhexlify(bgcolor[1:])

def is_bgcolor(bgcolor):
    try:
        parse_bgcolor(bgcolor)
    except Exception as e:
        return False
    else:
        return True

This accepts 3-character hex strings (but then so do most data formats that use #-prefixed hex RGB), and even 16-character ones. If you want to add a check for the length, you can add that. Is the rule == 6 or in (3, 6) or % 3 == 0? I don't know, but presumably you do if you have a rule you want to add.

If you start using parse_bgcolor, you'll discover that it's giving you a bytes with 6 values from 0-255, when you really wanted 3 values from 0-65535. You can combine them manually, or you can parse each two-character pair as a number (e.g., with int(pair, 16)), or you can feed the 6-char bytes you already have into, say, struct.unpack('>HHH'). Whatever you need to do is pretty easy once you know exactly what you want to do.

Finally, if you're trying to parse CSS or HTML, things like red or rgb(1, 2, 3) are also valid colors. Do you need to handle those? If so, you'll need something a bit smarter than this. The first thing to do is look at the spec for what you're trying to parse, and work out the rules you need to turn into code. Then you can write the code.

like image 105
abarnert Avatar answered Nov 25 '25 00:11

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!