import re


def shape_CEP(record):
    """Takes a brazilian CEP as a string and returns isself if CEP is correctly formatted, 
    formats properly if missing the '-' and returns none otherwise."""
    record = record.strip('CEP')
    record = record.strip()
    proper_CEP = '^([0-9]){5}([-])([0-9]){3}$'
    bad_dash = '^([0-9]){5}([.\s])([0-9]){3}$'
    dash_and_spaces = '^([0-9]){5}([\s][-][\s])([0-9]){3}$'     
    no_dash = '^([0-9]){8}$'
    if re.match(proper_CEP, record):
        return record
        #if CEP is properly formatted, return itself
    elif re.match(no_dash, record):
        return record[:5] + '-' + record[5:]
    elif re.match(bad_dash, record):
        return record[:5] + '-' + record[6:]
    elif re.match(dash_and_spaces, record):
        return record[:5] + '-' + record[8:]
    else:
        return None