我想从电子邮件中删除所有特殊字符,例如“@”、“.”并用“下划线”替换它们。
在Python中有一些函数可以实现这一功能,如'unidecode',但它不能完全满足我的要求。有人能建议我一种方法,以便我可以在字符串中找到上述提到的字符,并用“下划线”替换它们。
谢谢。
谢谢。
a='testemail@email.com'
a.replace('@','_')
'testemail_email.com'
a='testemail@email.com'
replace=['@','.']
for i in replace:
a=a.replace(i,'_')
import re
a = re.sub(u'[@]', '"', a)
语法:
re.sub(pattern, repl, string, max=0)
re.sub(r'[^a-zA-Z0-9]', '_', email)
的代码应该将an-example@example.com
转换为an_example_example_com
。 - undefinedPython Cookbook第二版的一个很好的例子
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("me-and_you@gmail.com")
输出:
me~and~you~gmail~com
这是一个非常实用的字符串工具,值得加入你的工具包。
所有功劳归 该书 所有。