我想从电子邮件中删除所有特殊字符,如'@','。'并用'下划线'替换它们 在python'unidecode'中有一些函数,但它不能完全满足我的要求。任何人都可以给我一些建议,这样我就可以在字符串中找到上述提及的字符,并用'下划线'替换它们。从django中的字符串中删除特殊字符
谢谢。
我想从电子邮件中删除所有特殊字符,如'@','。'并用'下划线'替换它们 在python'unidecode'中有一些函数,但它不能完全满足我的要求。任何人都可以给我一些建议,这样我就可以在字符串中找到上述提及的字符,并用'下划线'替换它们。从django中的字符串中删除特殊字符
谢谢。
为什么不使用.replace()
?
例如。
a='[email protected]'
a.replace('@','_')
'testemail_email.com'
和编辑多你可能可以这样做,从Python的食谱第2版此
a='[email protected]'
replace=['@','.']
for i in replace:
a=a.replace(i,'_')
很好的例子
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
但替换只需要两个参数txt.replace('@','_')如果我想删除多于一个字符,该怎么办 – Inforian
@Inforian看看编辑 – Jonathan
是的,它的工作原理,谢谢 – Inforian