码迷,mamicode.com
首页 > 其他好文 > 详细

转换为系统支持的字符串

时间:2018-08-10 10:58:47      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:otherwise   turn   sys   returns   represent   port   The   支持   type   

import sys

builtin_str = str
ver = sys.version
is_py2 = int(ver[0]) == 2
is_py3 = int(ver[0]) == 3


def to_native_string(string, encoding=‘ascii‘):
"""Given a string object, regardless of type, returns a representation of
that string in the native string type, encoding and decoding where
necessary. This assumes ASCII unless told otherwise.
"""
if isinstance(string, builtin_str):
out = string
else:
if is_py2:
out = string.encode(encoding)
# out = string.decode(encoding)
else:

out = string.decode(encoding)

return out


print to_native_string("just a test",‘utf-8‘)

转换为系统支持的字符串

标签:otherwise   turn   sys   returns   represent   port   The   支持   type   

原文地址:https://www.cnblogs.com/tnyleyon/p/9452851.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!