import re


def graphite_safe(string):
    """
    Sanitizes a string so that it can be used as part of a Graphite line.
    It does this by replacing non-alphanumeric characters with underscores.

    :param string: Your string to sanitize
    :return: Your sanitized string
    """
    # Convert whitespaces to underscores
    string = re.sub(r'\s', '_', string)
    # Convert non-alphanumeric characters to underscores
    string = re.sub(r'[^\w]', '_', string)
    # Collapse repeating underscores into one
    while '__' in string:
        string = string.replace('__', '_')
    return string