An isalpha() that accepts underscores as well

Fuzzyman fuzzyman at gmail.com
Sun Feb 26 14:32:20 EST 2006


Zajcev Evgeny wrote:
> egbert <egbert.bouwman at hccnet.nl> writes:
>
> > The string method isalpha() returns True when all characters in the
> > string are alphabetic. Unfortunately the underscore is not alphabetic.
> > A function that does what I need is:
> >
> > def alfa_(w):
> >     return "".join(w.split("_")).isalpha()
> >
> > but for the kind of strings that I have this is about ten times
> > slower than isalpha() sec. Any suggestions ?
> > Thanks.
>
> what about
>
>     def alfa_(w):
>         return w.isalpha() or w.find('_') != -1
>

That returns True if 'w' contains an underscore. The spec is to return
True if 'w' contains *only* alphaebtical characters and '_'.

alfa('%^_*&')

would return True here.

> ? but yes it does scan `w' twice ..
>
> You could also do something like:
>
>     def alfa_(w):
>         for c in w:
>             if not c.isalpha() and not c == '_':
>                return False
>         return True
>

Part of the problem is that the string method 'isalpha' is implemented
in C, and so will be  quicker than any pure Python alternative.

The following will work, and probably only be twice as slow as
'isalpha'  :-) :

def alfa(w):
   return w.replace('_', '').isalpha()

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> -- 
> lg




More information about the Python-list mailing list