python 在Unicode和普通字符串 str 之间转换


unicodestring = u"Hello world" # 将Unicode转化为普通Python字符串:"encode" utf8string = unicodestring.encode("utf-8") asciistring = unicodestring.encode("ascii") isostring = unicodestring.encode("ISO-8859-1") utf16string = unicodestring.encode("utf-16") # 将普通Python字符串转化为Unicode:"decode" plainstring1 = unicode(utf8string, "utf-8") plainstring2 = unicode(asciistring, "ascii") plainstring3 = unicode(isostring, "ISO-8859-1") plainstring4 = unicode(utf16string, "utf-16") assert plainstring1 == plainstring2 == plainstring3 == plainstring4

 

 

def unicode2str(p_unicode):
    v = p_unicode.encode('unicode-escape').decode('string_escape') if p_unicode is not None else None
    return v


def str2unicode(p_str):
    v = p_str.decode('unicode-escape') if p_str is not None else None
    return v

 

posted on 2018-04-02 15:44  星河赵  阅读(10442)  评论(0编辑  收藏  举报

导航