转换为系统支持的字符串

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')

posted @ 2018-08-10 08:40  tny_leyon  阅读(148)  评论(0编辑  收藏  举报