code: def as_binary(s, encoding='utf-8'):
      
      if isinstance(s, six.text_type):
          return s.encode(encoding)
      elif isinstance(s, six.binary_type):
          # make sure the binary is in required encoding
          return s.decode(encoding).encode(encoding)
      else:
          raise ValueError('Can only convert types {0} and {1}'.format(six.text_type, six.binary_type))
docs: Force conversion of given string to binary type.
      Binary is ``bytes`` type for Python 3.x and ``str`` for Python 2.x .
  
      If the string is already in binary, then no conversion is done and the same string is returned
      and ``encoding`` argument is ignored.
  
      Parameters
      ----------
      s: str or bytes (Python3), str or unicode (Python2)
          The string to convert to binary.
      encoding: str
          The encoding of the resulting binary string (default: utf-8)
  
      Raises
      ------
      ValueError
          In case an input of invalid type was passed to the function.
  
      Returns
      -------
      ``bytes`` for Python3 or ``str`` for Python 2.