def concatenate_replacements(text, replacements):
  """Applies a rewrite to some text and returns a span to be replaced.

  Args:
    text: Text to be rewritten.
    replacements: An iterable of (new_text, start of replacement, end)

  Returns:
    A new replacement.
  """
  joined = []
  first_start = None
  last_end = None
  for rewritten, start, end in replacements:
    if start > end:
      raise ValueError(
          'Rewrites have invalid spans: start=%r > end=%r' % (start, end))
    if first_start is None:
      first_start = start
    if last_end is not None:
      joined.append(text[last_end:start])
    if last_end is not None and last_end > start:
      raise ValueError(
          'Rewrites overlap: end > next start: '
          '{last_end} > {start}. '
          '(Was about to write: text[{start}:{end}] (== {old!r}) <- {new!r})'
          .format(
              start=start,
              end=end,
              last_end=last_end,
              old=text[start:end],
              new=rewritten))
    joined.append(rewritten)
    last_end = end
  return ''.join(joined), first_start or 0, last_end or 0