2017-05-29 324 views
0

说我有这样的如何在Python中替换unicode中文字符?

example = u"这是一段很蛋疼的中文" 

我想更换egg一个字符串,我怎么能完成呢?

看来example.replace()是无用的。 而我试过正则表达式,使用re.match(u"蛋", "")返回无。

我搜索了很多,看来我应该使用像.decode这样的方法,但它仍然不起作用,即使example.replace(u"\u86CB", "egg")也没用。

那么有没有办法处理汉字?

+0

你使用哪个版本的Python? – Vej

+2

它工作正常(我使用Python3.5)。替换函数不会更改原始字符串。如果你想改变原始字符串,你应该使用'example = example.replace(u'蛋','egg')'。 – TsReaper

+1

如果你还没有使用它,你应该切换到Python 3. – Ryan

回答

1

你应该得到的输出如下面Python3。

>>> import re 
>>> example = u"这是一段很蛋疼的中文" 
>>> re.search(u'蛋',example) 
<_sre.SRE_Match object; span=(5, 6), match='蛋'> 

>>> example.replace('蛋','egg') 
'这是一段很egg疼的中文' 
>>> re.sub('蛋','egg',example) 
'这是一段很egg疼的中文' 

>>> example.replace(u"\u86CB", "egg") 
'这是一段很egg疼的中文' 
>>> re.match('.*蛋',example) 
<_sre.SRE_Match object; span=(0, 6), match='这是一段很蛋'> 

re.match将尝试从一开始匹配字符串,因此它会在你的情况下返回None

+0

非常感谢!这是因为我尝试了我的正则表达式[正则表达式测试人员](https://regex101.com/),现在我知道,非常感谢! – JiangFeng

1

可以内Python2做这样的事情:

编辑:添加具有同样使用unicode literals将解决这一问题的编码规范中的一个正确编码的源文件。

#!/usr/local/bin/python 
# -*- coding: utf-8 -*- 

example = u"这是一段很蛋疼的中文" 
print example.replace(u"这", u"egg") 
# Within Python3 
# print(example.replace("这", 'egg')) 

输出:

egg是一段很蛋疼的中文 
+1

我使用的是Python 3,我发现原因是替换函数并没有改变原始字符串。非常感谢! – JiangFeng