import re


def quote(input_str, specials, escape='\\'):
  """Returns a quoted version of |str|, where every character in the
  iterable |specials| (usually a set or a string) and the escape
  character |escape| is replaced by the original character preceded by
  the escape character."""

  assert len(escape) == 1

  # Since escape is used in replacement pattern context, so we need to
  # ensure that it stays a simple literal and cannot affect the \1
  # that will follow it.
  if escape == '\\':
    escape = '\\\\'
  if len(specials) > 0:
    return re.sub(r'(' + r'|'.join(specials)+r'|'+escape + r')',
                  escape + r'\1', input_str)
  return re.sub(r'(' + escape + r')', escape + r'\1', input_str)