import textwrap


def reindent(text, indent):
  """
  Dedents *text* and then re-indents it with the specified *indent*. The
  *indent* parameter must be a string.
  """

  lines = textwrap.dedent(text).split('\n')
  while lines and not lines[0].strip():
    lines.pop(0)
  while lines and not lines[-1].strip():
    lines.pop()
  return indent + ('\n' + indent).join(lines)