Encodes <unicode> into byte <str>. Replaces any non utf8 chars

def safely_encode(unicode_or_str, encoding='utf-8'):
  ''' Encodes <unicode> into byte <str>. Replaces any non utf8 chars '''
  if isinstance(unicode_or_str, unicode):
    rstr = unicode_or_str.encode(encoding, 'replace')
  elif isinstance(unicode_or_str, str):
    rstr = unicode_or_str
  else:
    raise Exception(u'Not of type unicode or str')

  return rstr