def unicode_to_str(unicode_str):
return unicode_str.encode().decode('unicode_escape')
def str_to_unicode(string):
new_str = ''
for ch in string:
if '\u4e00' <= ch <= '\u9fff':
new_str += hex(ord(ch)).replace('0x', '\\u')
else:
new_str += ch
return new_str
if __name__ == '__main__':
unicode = str_to_unicode('你好')
print(unicode) # \u4f60\u597d
print(repr(unicode)) # '\\u4f60\\u597d'
print(unicode_to_str('\\u4f60\\u597d')) # 你好
【Python】字符串与unicode字符之间的转换
于 2022-08-07 20:21:00 首次发布
本文介绍了如何使用Python将unicode字符串转换为普通字符串(unicode_to_str函数),以及如何通过正则表达式将包含Unicode转义字符的字符串解码回原始文本(str_to_unicode函数)。通过实例展示了在主函数中处理'你好'字符的转换过程。
712

被折叠的 条评论
为什么被折叠?



