1

I am using the following class to format integers and string values into a desired format as shown below:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

print(bcolors.WARNING + "Sample Warning Text. Continue?" + bcolors.ENDC)

However, my goal is to have a function such as:

color_format(input,format)

which would essentially make the use of formatting easier.

Is there an option to define an array of possible option in a function? E.g.

def color_format(input, format)
         format = [
                   HEADER = '\033[95m',
                   OKBLUE = '\033[94m',
                   OKGREEN = '\033[92m',
                   WARNING = '\033[93m',
                   FAIL = '\033[91m',
                   ENDC = '\033[0m',
                   BOLD = '\033[1m',
                   UNDERLINE = '\033[4m'
                   ]
          print(format + input + ENDC='\033[0m')
color_format("This is a bold text",BOLD)

~This is a bold text

I'd appreciate your help alot!

1 Answer 1

3

Yes, you can do this using dict with mapping from names to values.

FORMATS = {
    'HEADER': '\033[95m',
    'OKBLUE': '\033[94m',
    'OKGREEN': '\033[92m',
    'WARNING': '\033[93m',
    'FAIL': '\033[91m',
    'ENDC': '\033[0m',
    'BOLD': '\033[1m',
    'UNDERLINE': '\033[4m'
}

def color_format(text, format):
    try:
        formatted = FORMATS[format] + text + FORMATS['ENDC']
    except KeyError:
        print('Invalid format! Possible values are: ', FORMATS.keys())
    else:
        print(formatted)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.