Linux 如何在 Python 中将 u'\\u4f60\\u4f60' 之类的 unicode 字符串转换为 u'\u4f60\u4f60'?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3677213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:26:42 来源:igfitidea点击:
How to convert unicode string like u'\\u4f60\\u4f60' to u'\u4f60\u4f60' in Python?
提问by kols
I capture the string from a html source file using 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() 来完成吗?或者需要更复杂的东西?
采纳答案by kennytm
>>> u'\u4f60\u4f60'.decode('unicode_escape')
u'\u4f60\u4f60'