2013-02-07 163 views
1

我想从电子邮件中删除所有特殊字符,如'@','。'并用'下划线'替换它们 在python'unidecode'中有一些函数,但它不能完全满足我的要求。任何人都可以给我一些建议,这样我就可以在字符串中找到上述提及的字符,并用'下划线'替换它们。从django中的字符串中删除特殊字符

谢谢。

回答

3

为什么不使用.replace()

例如。

a='[email protected]' 
a.replace('@','_') 
'testemail_email.com' 

和编辑多你可能可以这样做,从Python的食谱第2版此

a='[email protected]' 
replace=['@','.'] 
for i in replace: 
    a=a.replace(i,'_') 
+0

但替换只需要两个参数txt.replace('@','_')如果我想删除多于一个字符,该怎么办 – Inforian

+0

@Inforian看看编辑 – Jonathan

+0

是的,它的工作原理,谢谢 – Inforian

1

以此为指南:

import re 
a = re.sub(u'[@]', '"', a) 

语法:

re.sub(pattern, repl, string, max=0) 
+0

你好凯蒂,取而代之的是比子 – Jonathan

+0

感谢更快速和它的作品,但以相反的方式......它正在取代**[email protected]**到**“”” “”@“”“”“。”“”** – Inforian

+1

看看[this](http://stackoverflow.com/questions/5668947/python-string-replace-vs-re-sub) – Jonathan

1

很好的例子

import string 
def translator(frm='', to='', delete='', keep=None): 
    if len(to) == 1: 
     to = to * len(frm) 
    trans = string.maketrans(frm, to) 
    if keep is not None: 
     allchars = string.maketrans('', '') 
     delete = allchars.translate(allchars, keep.translate(allchars, delete)) 
    def translate(s): 
     return s.translate(trans, delete) 
    return translate 


remove_cruft = translator(frm="@-._", to="~") 
print remove_cruft("[email protected]") 

输出:

me~and~you~gmail~com 

伟大string util放入你的工具包。

所有信贷the book

相关问题