An isalpha() that accepts underscores as well
Zajcev Evgeny
zevlg at yandex.ru
Sun Feb 26 14:45:13 EST 2006
"Fuzzyman" <fuzzyman at gmail.com> writes:
> 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 '_'.
>
true, my fault :-< !
> 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.
>
I've been suspecting this ..
> The following will work, and probably only be twice as slow as
> 'isalpha' :-) :
>
> def alfa(w):
> return w.replace('_', '').isalpha()
Yeah, great performance indeed, thanks!
--
lg
More information about the Python-list
mailing list