def safe_string(s):
  """Safely converts unicode and plain strings to byte strings."""
  if isinstance(s, str):
    try:
      s = s.encode('utf-8')
    except UnicodeDecodeError:
      s = repr(s)
  return s