I have the following code:
import string
def translate_non_alphanumerics(to_translate, translate_to=\'_\'):
not_letters_or_digits = u\'!\"#%\\\'()*+,-./:
I came up with the following combination of my original function and Mike's version that works with Unicode and ASCII strings:
def translate_non_alphanumerics(to_translate, translate_to=u'_'):
not_letters_or_digits = u'!"#%\'()*+,-./:;<=>?@[\]^_`{|}~'
if isinstance(to_translate, unicode):
translate_table = dict((ord(char), unicode(translate_to))
for char in not_letters_or_digits)
else:
assert isinstance(to_translate, str)
translate_table = string.maketrans(not_letters_or_digits,
translate_to
*len(not_letters_or_digits))
return to_translate.translate(translate_table)
Update: "coerced" translate_to to unicode for the unicode translate_table. Thanks Mike.