def safe_str(s, known_words=None):
    """return ``s`` as `str` safe to `eval` or raise an exception.

    Strings in the `dict` `known_words` are replaced by their values
    surrounded with a space, which the caller considers safe to evaluate
    with `eval` afterwards.

    Known issues:

    >>> try: from cma.purecma import safe_str
    ... except ImportError: from purecma import safe_str
    >>> safe_str('int(p)', {'int': 'int', 'p': 3.1})  # fine
    ' int ( 3.1 )'
    >>> safe_str('int(n)', {'int': 'int', 'n': 3.1})  # unexpected
    ' i 3.1 t ( 3.1 )'

    """
    safe_chars = ' 0123456789.,+-*()[]e'
    if s != str(s):
        return str(s)
    if not known_words:
        known_words = {}
    stest = s[:]
    sret = s[:]
    for word in sorted(known_words.keys(), key=len, reverse=True):
        stest = stest.replace(word, '  ')
        sret = sret.replace(word, ' %s ' % known_words[word])
    for c in stest:
        if c not in safe_chars:
            raise ValueError(
                '"%s" is not a safe string (known words are %s)' % (s, str(
                known_words)))
    return sret
