code: def substitute(self, msg, kind):
          
  
          # Safety checking.
          if 'lists' not in self.master._sorted:
              raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents")
          if kind not in self.master._sorted["lists"]:
              raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents")
  
          # Get the substitution map.
          subs = None
          if kind == 'sub':
              subs = self.master._sub
          else:
              subs = self.master._person
  
          # Make placeholders each time we substitute something.
          ph = []
          i  = 0
  
          for pattern in self.master._sorted["lists"][kind]:
              result = subs[pattern]
  
              # Make a placeholder.
              ph.append(result)
              placeholder = "\x00%d\x00" % i
              i += 1
  
              cache = self.master._regexc[kind][pattern]
              msg = re.sub(cache["sub1"], placeholder, msg)
              msg = re.sub(cache["sub2"], placeholder + r'\1', msg)
              msg = re.sub(cache["sub3"], r'\1' + placeholder + r'\2', msg)
              msg = re.sub(cache["sub4"], r'\1' + placeholder, msg)
  
          placeholders = re.findall(RE.placeholder, msg)
          for match in placeholders:
              i = int(match)
              result = ph[i]
              msg = msg.replace('\x00' + match + '\x00', result)
  
          # Strip & return.
          return msg.strip()
docs: Run a kind of substitution on a message.
  
          :param str msg: The message to run substitutions against.
          :param str kind: The kind of substitution to run,
              one of ``subs`` or ``person``.