def METHOD_NAME(term):
    # Only surround with quotes if the term contains whitespace
    if whitespace.intersection(term):
        # Originally double quoted and contained escaped double quotes
        if '\\"' in term:
            return '"' + term + '"'
        # Originally single quoted and contained escaped single quotes
        if "\\'" in term:
            return "'" + term + "'"
        # Contains unescaped single quotes, so easiest to double quote
        if "'" in term:
            return '"' + term + '"'
        # None of the above: prefer single quotes
        return "'" + term + "'"
    return term