code: def _urlquote(string, safe=''):
      
  
      if string is None or string == '':
          return None
  
      # Anything already hex quoted is pulled out of the URL and unquoted if
      # possible
      escapes = []
      if re.search('%[0-9a-fA-F]{2}', string):
          # Try to unquote any percent values, restoring them if they are not
          # valid UTF-8. Also, requote any safe chars since encoded versions of
          # those are functionally different than the unquoted ones.
          def _try_unescape(match):
              byte_string = unquote_to_bytes(match.group(0))
              unicode_string = byte_string.decode('utf-8', 'iriutf8')
              for safe_char in list(safe):
                  unicode_string = unicode_string.replace(safe_char, '%%%02x' % ord(safe_char))
              return unicode_string
          string = re.sub('(?:%[0-9a-fA-F]{2})+', _try_unescape, string)
  
          # Once we have the minimal set of hex quoted values, removed them from
          # the string so that they are not double quoted
          def _extract_escape(match):
              escapes.append(match.group(0).encode('ascii'))
              return '\x00'
          string = re.sub('%[0-9a-fA-F]{2}', _extract_escape, string)
  
      output = urlquote(string.encode('utf-8'), safe=safe.encode('utf-8'))
      if not isinstance(output, byte_cls):
          output = output.encode('ascii')
  
      # Restore the existing quoted values that we extracted
      if len(escapes) > 0:
          def _return_escape(_):
              return escapes.pop(0)
          output = re.sub(b'%00', _return_escape, output)
  
      return output
docs: Quotes a unicode string for use in a URL
  
      :param string:
          A unicode string
  
      :param safe:
          A unicode string of character to not encode
  
      :return:
          None (if string is None) or an ASCII byte string of the quoted string