Search code examples
pythonreplaceord

Referencing list to remove string values


The following def clean_sheet_title function references INVALID_TITLE_CHAR and INVALID_TITLE_CHAR_MAP to strip out invalid characters and limits the title to 31 characters -

# This strips characters that are invalid to Excel
INVALID_TITLE_CHARS = ["]", "[", "*", ":", "?", "/", "\\", "'"]
INVALID_TITLE_CHAR_MAP = {ord(x): "" for x in INVALID_TITLE_CHARS}

# How would I remove strings, as well as the characters from INVALID_TITLE_CHARS?
INVALID_TITLE_NAMES = ["zz_ FeeRelationship", " Family"]

def clean_sheet_title(title):
    title = title or ""
    title = title.strip()
    title = title.translate(INVALID_TITLE_CHAR_MAP)
    return title[:31]

My question is how I would expand this to also remove strings from within the INVALID_TITLE_NAMESlist?

What I've tried: I have tried making the following update to def clean_sheet_title however this makes no difference to title -

INVALID_TITLE_CHARS = ["]", "[", "*", ":", "?", "/", "\\", "'"]
INVALID_TITLE_CHAR_MAP = {ord(x): "" for x in INVALID_TITLE_CHARS}

INVALID_TITLE_NAMES = ["zz_ FeeRelationship", "Family"]


def clean_sheet_title(title):
    title = title or ""
    title = title.strip()
    title = title.translate(INVALID_TITLE_CHAR_MAP, "")
    for name in INVALID_TITLE_NAMES:
        title = title.replace(name, "")
    return title[:31]

Examples:

  • Current function ability - if title == Courtenay:Family then currently the def clean_sheet_title will ensure the title will be Courtenay Family.

  • Desired function ability - Sometimes title can be prefixed or suffixed with either zz_ FeeRelationship or Family, in both cases, these strings should be dropped. E.g. zz_ FeeRelationship Courtenay:Family would become Courtenay


Solution

  • Try this:

    for name in INVALID_TITLE_NAMES:
        title = title.replace(name, "")
    

    Is that the result you are trying to achieve? It should replace each invalid name in title with an empty string.