本文整理汇总了Python中string.encode函数的典型用法代码示例。如果您正苦于以下问题:Python encode函数的具体用法?Python encode怎么用?Python encode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了encode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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()
示例3: only_iso88591
def only_iso88591(self, string):
flag = True
try:
string.encode("iso-8859-1")
except UnicodeEncodeError:
flag = False
return flag
示例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)
示例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
示例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
示例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
示例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
示例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()
示例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))
示例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
示例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
示例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.")
示例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
示例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