#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2000
    Location
    Southern California
    Posts
    73
    Rep Power
    15

    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?
  2. #2
  3. Wacky hack
    Devshed Novice (500 - 999 posts)

    Join Date
    Apr 2001
    Location
    London, England
    Posts
    513
    Rep Power
    14
    Look into the re module. It should do all you need.

    Also, this page is really handy if you, like me, are coming from Perl to Python:

    http://starship.python.net/~da/jak/cookbook.html

IMN logo majestic logo threadwatch logo seochat tools logo