Python - How to check if string is a HEX Color Code

Fragkiller picture Fragkiller · May 14, 2015 · Viewed 10.9k times · Source

I need your help!

Im kinda new whats regarding python and "hex".

I have a site where people can enter their own HEX-Color for their messages.

So currently i have everything built in except the "isHEXColor" Check..

I realy dont know how i can be sure that the user gave a valid HEX-Color-Code.

Currently im just checking if the len is 6 digits, nothing more.

if not len(color) == 6: return error("HEX-Color" must contain 6 characters")

Can you might help me? And it should work for Python 2.5!

Answer

teoreda picture teoreda · May 14, 2015

You could use a regular expression:

^#(?:[0-9a-fA-F]{3}){1,2}$

For using regular expression in python https://docs.python.org/2/library/re.html

import re
str = '#ffffff' # Your Hex

match = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', str)

if match:                      
  print 'Hex is valid'

else:
  print 'Hex is not valid'