转换为系统支持的字符串

Posted tnyleyon

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了转换为系统支持的字符串相关的知识,希望对你有一定的参考价值。

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














以上是关于转换为系统支持的字符串的主要内容,如果未能解决你的问题,请参考以下文章