• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python string.encode函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中string.encode函数的典型用法代码示例。如果您正苦于以下问题:Python encode函数的具体用法?Python encode怎么用?Python encode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了encode函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _encode

def _encode(string, encoding):
    if sys.version_info[0] > 2:
        return string.encode(encoding=encoding, errors='strict')
    else:
        if type(u('')) == type(string):
            string = string.encode(encoding)
        return string
开发者ID:Farik013,项目名称:my-first-blog,代码行数:7,代码来源:static.py


示例2: log

	def log(self, header, string):
		f = open(self._log, 'a+')
		f.write(header.encode( "utf-8" ) + string.encode( "utf-8" ))
		print header.encode( "utf-8" ) + string.encode( "utf-8" )
		print "\n"
		f.write("\n")
		f.close()
开发者ID:edgarskos,项目名称:wikiro,代码行数:7,代码来源:wiki2osm_links2.py


示例3: only_iso88591

	def only_iso88591(self, string):
		flag = True
		try:
			string.encode("iso-8859-1")
		except UnicodeEncodeError:
			flag = False

		return flag
开发者ID:cltk,项目名称:cltk_api,代码行数:8,代码来源:text.py


示例4: encode

 def encode(self, string):
     clean_sentence_unwantedchars= '["\t\n ]+'
     string = string.encode('utf8')
     string = string.decode('utf-8')    
     string = re.sub(clean_sentence_unwantedchars, ' ', string)
     string = string.encode('ascii', 'replace').encode('utf-8')
     string = string.decode('utf-8')
     return str(string)    
开发者ID:alihashmi01,项目名称:frame,代码行数:8,代码来源:grammarmodule.py


示例5: getHtml

 def getHtml(self, url):
     try:
         request_score = urllib2.Request(url, headers=self.headers)
         response_score = self.opener.open(request_score)
         print('claw page')
         return response_score.read().decode("gb2312", 'ignore').encode("utf8")
     except urllib2.URLError, e:
         if hasattr(e, "reason"):
             string = "连接bbs 失败, 原因" +  str(e.reason)
             print string.encode(self.charaterset)
             return None
开发者ID:Juntaran,项目名称:Python,代码行数:11,代码来源:教务爬虫.py


示例6: create

	def create(cls, app, redirect_uri = None):
		now = datetime.utcnow().replace(tzinfo=utc)
		code_expires = now + timedelta(minutes = 10)
		string = app.client_id
		code = hashlib.sha224(string.encode('utf-8') + now.strftime(settings.DATE_FORMAT).encode('utf-8')).hexdigest()
		token = cls(app_id=app, code=code, code_expires=code_expires, redirect_uri=redirect_uri)
		return token
开发者ID:nikozavr,项目名称:rsoi-lab,代码行数:7,代码来源:models.py


示例7: aimlize

	def aimlize(self, string):
		self.steps = []
		string  = string.encode('utf-8')
		for(module) in self.modules:
			string = module.process(string)
			self.steps.append(module.getModuleName()+": "+string)
		return string
开发者ID:alexanderbazo,项目名称:urtalking,代码行数:7,代码来源:aimlizer.py


示例8: sign

	def sign(self):
		string = '&'.join(['%s=%s' % (key.lower(), self.ret[key]) for key in sorted(self.ret)])
		logger.debug('string:%s' % (string))
		signature = hashlib.sha1(string.encode('utf8')).hexdigest()
		self.ret['signature'] = signature
		logger.debug('signature:%s' % (signature))
		return self.ret
开发者ID:imycart,项目名称:imycart,代码行数:7,代码来源:sign.py


示例9: hash_string

def hash_string(string):
    """
    Convenience wrapper that returns the hash of a string.
    """
    assert isinstance(string, str), f'{string} is not a string!'
    string = string.encode('utf-8')
    return sha256(string).hexdigest()
开发者ID:ericmjl,项目名称:data-testing-tutorial,代码行数:7,代码来源:datafuncs_soln.py


示例10: _header

    def _header(self, r):
        """ Build the contents of the X-NFSN-Authentication HTTP header. See
        https://members.nearlyfreespeech.net/wiki/API/Introduction for
        more explanation. """
        login = self.login
        timestamp = self._timestamp()
        salt = self._salt()
        api_key = self.api_key
        request_uri = urlparse(r.url).path
        body = ''.encode('utf-8')
        if r.body:
            body = r.body.encode('utf-8')
        body_hash = hashlib.sha1(body).hexdigest()

        log.debug("login: %s", login)
        log.debug("timestamp: %s", timestamp)
        log.debug("salt: %s", salt)
        log.debug("api_key: %s", api_key)
        log.debug("request_uri: %s", request_uri)
        log.debug("body_hash: %s", body_hash)

        string = ';'.join((login, timestamp, salt, api_key, request_uri, body_hash))
        log.debug("string to be hashed: %s", string)
        string_hash = hashlib.sha1(string.encode('utf-8')).hexdigest()
        log.debug("string_hash: %s", string_hash)

        return ';'.join((login, timestamp, salt, string_hash))
开发者ID:ktdreyer,项目名称:python-nfsn,代码行数:27,代码来源:auth.py


示例11: update

    def update(self, view):
        if not self.need_upd:
            return
        self.need_upd = False

        color_scheme_path = self.color_scheme_path(view)
        if not color_scheme_path:
            return
        packages_path, cs = color_scheme_path
        cont = self.get_color_scheme(packages_path, cs)

        current_colors = set("#%s" % c for c in re.findall(r'<string>%s(.*?)</string>' % self.prefix, cont, re.DOTALL))

        string = ""
        for col, name in self.colors.items():
            if col not in current_colors:
                fg_col = self.get_fg_col(col)
                string += self.gen_string % (self.name, name, col, fg_col, fg_col)

        if string:
            # edit cont
            n = cont.find("<array>") + len("<array>")
            try:
                cont = cont[:n] + string + cont[n:]
            except UnicodeDecodeError:
                cont = cont[:n] + string.encode("utf-8") + cont[n:]

            self.write_file(packages_path, cs, cont)
            self.need_restore = True
开发者ID:Kronuz,项目名称:ColorHighlighter,代码行数:29,代码来源:ColorHighlighter.py


示例12: normalize

def normalize(string):
	string = string.replace(u"Ä", "Ae").replace(u"ä", "ae")
	string = string.replace(u"Ö", "Oe").replace(u"ö", "oe")
	string = string.replace(u"Ü", "Ue").replace(u"ü", "ue")
	string = string.replace(u"ß", "ss")
	string = string.encode("ascii", "ignore")
	return string
开发者ID:raumzeitlabor,项目名称:rzlphlog,代码行数:7,代码来源:rzlphlog.py


示例13: send_raw

    def send_raw(self, string):
        """Send raw string to the server.

        The string will be padded with appropriate CR LF.
        """
        # The string should not contain any carriage return other than the
        # one added here.
        if '\n' in string:
            raise InvalidCharacters(
                "Carriage returns not allowed in privmsg(text)")
        bytes = string.encode('utf-8') + b'\r\n'
        # According to the RFC http://tools.ietf.org/html/rfc2812#page-6,
        # clients should not transmit more than 512 bytes.
        if len(bytes) > 512:
            raise MessageTooLong(
                "Messages limited to 512 bytes including CR/LF")
        if self.socket is None:
            raise ServerNotConnectedError("Not connected.")
        sender = getattr(self.socket, 'write', self.socket.send)
        try:
            sender(bytes)
            log.debug("TO SERVER: %s", string)
        except socket.error:
            # Ouch!
            self.disconnect("Connection reset by peer.")
开发者ID:pouwapouwa,项目名称:PyRScie,代码行数:25,代码来源:client.py


示例14: _canonical_string_encoder

def _canonical_string_encoder(string):
  """
  <Purpose>
    Encode 'string' to canonical string format.
    
  <Arguments>
    string:
      The string to encode.

  <Exceptions>
    None.

  <Side Effects>
    None.

  <Returns>
    A string with the canonical-encoded 'string' embedded.

  """

  string = '"%s"' % re.sub(r'(["\\])', r'\\\1', string)
  if isinstance(string, unicode):
    return string.encode('utf-8')
  else:
    return string
开发者ID:pombredanne,项目名称:tuf,代码行数:25,代码来源:formats.py


示例15: default_filter_hex

def default_filter_hex(pattern, value):
   if value == 0:
      return False
   string = struct.pack(pattern.packchar, value)
   hexstr = string.encode('hex')
   if hexstr.count('00') > pattern.size/2:
      return False
   return True
开发者ID:timhsutw,项目名称:glassdog,代码行数:8,代码来源:glassdog.py


示例16: make_safe_digest

def make_safe_digest(string: str,
                     hash_func: Callable[[bytes], Any]=hashlib.sha1) -> str:
    """
    return a hex digest of `string`.
    """
    # hashlib.sha1, md5, etc. expect bytes, so non-ASCII strings must
    # be encoded.
    return hash_func(string.encode('utf-8')).hexdigest()
开发者ID:akashnimare,项目名称:zulip,代码行数:8,代码来源:utils.py


示例17: unquote_plus

def unquote_plus(string, encoding='utf-8', errors='strict'):
    '''``urllib.parse.unquote_plus`` with Python 2 compatbility.'''
    if sys.version_info[0] == 2:
        return urllib.parse.unquote_plus(
            string.encode(encoding, errors)
        ).decode(encoding, errors)
    else:
        return urllib.parse.unquote_plus(string, encoding, errors)
开发者ID:lowks,项目名称:wpull,代码行数:8,代码来源:url.py


示例18: send_raw

	def send_raw(self, string):
		"""Send raw string to the server.

		The string will be padded with appropriate CR LF.
		"""
		if self.socket is None:
			raise ServerNotConnectedError, "Not connected."
		try:
			if self.ssl:
				self.ssl.write(string.encode('utf-8', 'ignore') + "\r\n")
			else:
				self.socket.send(string.encode('utf-8', 'ignore') + "\r\n")
			if DEBUG:
				print "TO SERVER:", string
		except socket.error, x:
			# Ouch!
			self.disconnect("Connection reset by peer.")
开发者ID:Oscillope,项目名称:GumBot,代码行数:17,代码来源:irclib.py


示例19: sign

	def sign(self):
		ticket = self.get_ticket()
		self.ret['jsapi_ticket'] = ticket	
		string = '&'.join(['%s=%s' % (key.lower(), self.ret[key]) for key in sorted(self.ret)])
		logger.debug('string:%s' % (string))
		signature = hashlib.sha1(string.encode('utf8')).hexdigest()
		self.ret['signature'] = signature
		logger.debug('signature:%s' % (signature))
		return self.make_wechat_config()
开发者ID:imycart,项目名称:imycart,代码行数:9,代码来源:wechat.py


示例20: mb_code

def mb_code(string, coding="utf-8"):
    if isinstance(string, unicode):
        return string.encode(coding)
    for c in ('utf-8', 'gb2312', 'gbk', 'gb18030', 'big5'):
        try:
            return string.decode(c).encode(coding)
        except:
            pass
    return string
开发者ID:ifduyue,项目名称:buaatreeholes,代码行数:9,代码来源:lib.py



注:本文中的string.encode函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python string.endswith函数代码示例发布时间:2022-05-27
下一篇:
Python string.decode函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap