code: def _format_assertmsg(obj):
      
      # reprlib appears to have a bug which means that if a string
      # contains a newline it gets escaped, however if an object has a
      # .__repr__() which contains newlines it does not get escaped.
      # However in either case we want to preserve the newline.
      if py.builtin._istext(obj) or py.builtin._isbytes(obj):
          s = obj
          is_repr = False
      else:
          s = py.io.saferepr(obj)
          is_repr = True
      if py.builtin._istext(s):
          t = py.builtin.text
      else:
          t = py.builtin.bytes
      s = s.replace(t("\n"), t("\n~")).replace(t("%"), t("%%"))
      if is_repr:
          s = s.replace(t("\\n"), t("\n~"))
      return s
docs: Format the custom assertion message given.
  
      For strings this simply replaces newlines with '\n~' so that
      util.format_explanation() will preserve them instead of escaping
      newlines.  For other objects py.io.saferepr() is used first.