unicode和中文汉字之间的转换

直接上代码:

#!usr/bin/env python
#coding: utf-8

'''
'\u4e2d\u56fd'转换成中国
'''
def decodestr(str1):
    try:
        print("执行结果:")
        str1 = str1.decode('unicode_escape')
        print str1
    except :
        return None

if __name__ == "__main__":
    str1 = '\u4e2d\u56fd'
    decodestr(str1)

#!usr/bin/env python
#coding: utf-8

'''
    中国转换成'\u4e2d\u56fd'
'''
def encodestr(str1):
    try:
        print("执行结果:")
        str1 = str1.encode('unicode_escape')
        print str1
    except :
        return None

if __name__ == "__main__":
    str1 = u'中国'
    encodestr(str1)


你可能感兴趣的:(Python)