March 12th, 2003, 04:57 PM
-
python equivalents
I am converting a perl module for filtering form input into a python equivalent, and need the python equivalent of the perl 'tr' operator. I came up with some routines (below), but wondered if there was a better way?
These are the some of the perl routines:
Code:
sub squeeze_ws {
my $str = shift;
$str =~ tr/ / /s;
return $str;
}
sub force_int {
my $str = shift;
$str =~ tr/0-9//cd;
return $str;
}
sub force_alpha {
my $str = shift;
$str =~ tr/0-9a-zA-Z//cd;
return $str;
}
sub force_char {
my $str = shift;
$str =~ tr/a-zA-Z//cd;
return $str;
}
And here is the python equivalent:
Code:
class Filter(object):
def __init__(self):
pass
def chop_blanks(s):
return s.strip()
def squeeze_ws(s):
s = s.expandtabs()
a = s.split(' ')
return ' '.join([i for i in a if i and not i.isspace()])
def force_int(s):
return Filter.trcd(s, range(0,9))
def force_alpha(s):
chars = "abcdefghijklmnopqrstuvwxyz" \
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
"0123456789"
return Filter.trcd(s, chars)
def force_char(s):
chars = "abcdefghijklmnopqrstuvwxyz" \
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return Filter.trcd(s, chars)
def trcd(s, keep):
allchars = string.maketrans('', '')
delchars = ''.join([c for c in allchars if c not in keep])
return s.translate(allchars, delchars)
chop_blanks = staticmethod(chop_blanks)
# ...
Any thoughts?
March 12th, 2003, 06:22 PM
-