docs: def replace(self, old, new, start=None, end=None, count=None,
                  bytealigned=None):
          """Replace all occurrences of old with new in place.
  
          Returns number of replacements made.
  
          old -- The bitstring to replace.
          new -- The replacement bitstring.
          start -- Any occurrences that start before this will not be replaced.
                   Defaults to 0.
          end -- Any occurrences that finish after this will not be replaced.
                 Defaults to self.len.
          count -- The maximum number of replacements to make. Defaults to
                   replace all occurrences.
          bytealigned -- If True replacements will only be made on byte
                         boundaries.
  
          Raises ValueError if old is empty or if start or end are
          out of range.
  
          """
          old = Bits(old)
          new = Bits(new)
          if not old.len:
              raise ValueError("Empty bitstring cannot be replaced.")
          start, end = self._validate_slice(start, end)
          if bytealigned is None:
              bytealigned = globals()['bytealigned']
          # Adjust count for use in split()
          if count is not None:
              count += 1
          sections = self.split(old, start, end, count, bytealigned)
          lengths = [s.len for s in sections]
          if len(lengths) == 1:
              # Didn't find anything to replace.
              return 0 # no replacements done
          if new is self:
              # Prevent self assignment woes
              new = copy.copy(self)
          positions = [lengths[0] + start]
          for l in lengths[1:-1]:
              # Next position is the previous one plus the length of the next section.
              positions.append(positions[-1] + l)
          # We have all the positions that need replacements. We do them
          # in reverse order so that they won't move around as we replace.
          positions.reverse()
          try:
              # Need to calculate new pos, if this is a bitstream
              newpos = self._pos
              for p in positions:
                  self[p:p + old.len] = new
              if old.len != new.len:
                  diff = new.len - old.len
                  for p in positions:
                      if p >= newpos:
                          continue
                      if p + old.len <= newpos:
                          newpos += diff
                      else:
                          newpos = p
              self._pos = newpos
          except AttributeError:
              for p in positions:
                  self[p:p + old.len] = new
          assert self._assertsanity()
          return len(lengths) - 1