如何在Python中将u'\\ u4f60 \\ u4f60'之类的unicode字符串转换为u'\ u4f60 \ u4f60'?

时间:2010-09-09 13:54:44

标签: python unicode replace

我使用正则表达式从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()来完成吗?还是需要更复杂的东西?

1 个答案:

答案 0 :(得分:6)

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