NEWBIE: ishexdigit revisited

Kirk Strauser kirk at strauser.com
Tue Dec 30 11:25:06 EST 2003


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

At 2003-12-30T00:44:34Z, engsolnom at ipns.com writes:


>>4) You could also use a regular expression to test for hex digits:
>>
>>     def ishexnumber(sx):
>>         import re
>>         if not re.match('[0123456789abcdefABCDEF]*$', sx): return 0
>>         if len(sx) % 2 == 0: return 1
>>         return 'Extra nibble'

> If I run this many times, as is likely in our application, does the
> 'import re' chew up memory?

For production use, I'd factor out the 're' stuff (for performance) and add
descriptive variable names (it doesn't cost anything) like so:

    import re
    hexpattern = re.compile(r'[0123456789abcdefABCDEF]*$')

    def ishexnumber(checkstring):
        if not hexpattern.match(checkstring): return 0
        if not len(checkstring) % 2: return 1
        return 'Extra nibble'

That way, the pattern is only compiled once.
- -- 
Kirk Strauser
The Strauser Group
Open. Solutions. Simple.
http://www.strausergroup.com/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/8aa65sRg+Y0CpvERAlINAJoDMrDiTHdxtaF8aKNBf+KYjxdD6wCgm+UR
i4ZbaJklkaOzJ9TVQH5JMz0=
=bncS
-----END PGP SIGNATURE-----




More information about the Python-list mailing list