[Django]-Remove special chracters from a string in django

5👍

Why not use .replace() ?

eg.

a='testemail@email.com'
a.replace('@','_')
'testemail_email.com'

and to edit multiple you can probably do something like this

a='testemail@email.com'
replace=['@','.']
for i in replace:
  a=a.replace(i,'_')

1👍

Take this as a guide:

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

SYNTAX:

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

1👍

Great example from Python Cookbook 2nd edition

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")

output:

me~and~you~gmail~com

A great string util to put in your toolkit.

All credit to the book

Leave a comment