如何在Python中转换unicode字符串,如u'\\u4f60\ u4f60'到u'\u4f60\u4f60' ?

时间:2022-11-26 20:19:01

I capture the string from a html source file using regex:

我使用regex从html源文件捕获字符串:

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

And I've tried:

我已经试过:

>>> 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  

Could that be done by str.replace()? Or need something more complex?

可以用str.replace()来完成吗?还是需要更复杂的东西?

1 个解决方案

#1


6  

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

#1


6  

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