Skip to main content
 首页 » 编程设计

python之如何在 Python 中转换像 u'\\u4f60\\u4f6 0' to u'\u4f60\u4f60' 这样的 unicode 字符串

2025年05月04日32shanyou

我使用正则表达式从 html 源文件中捕获字符串:

f = open(rrfile, 'r') 
p = re.compile(r'"name":"([^"]+)","head":"([^"]+)"') 
match = re.findall(p, f.read()) 

我试过:

>>> u'\\u4f60\\u4f60'.replace('\\u', '\u')   
u'\\u4f60\\u4f60'   
>>> u'\\u4f60\\u4f60'.replace(u'\\u', '\u')   
u'\\u4f60\\u4f60'   
>>> u'\\u4f60\\u4f60'.replace('\\u', u'\u')   
File "<stdin>", line 1   
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: end of string in escape sequence   

这可以通过 str.replace() 来完成吗?或者需要更复杂的东西?

请您参考如下方法:

>>> u'\\u4f60\\u4f60'.decode('unicode_escape') 
u'\u4f60\u4f60'