Test String Contents

Peter Otten __peter__ at web.de
Tue Jun 13 21:08:36 EDT 2017


Peter Otten wrote:

> Matt wrote:
> 
>> What is easiest way to determine if a string ONLY contains a-z upper
>> or lowercase.  I also want to allow the "-" and "_" symbols.  No
>> spaces or anything else.
> 
> If you don't know regular expressions here's a method where not much can
> go wrong:

... with the exception of the empty string.

If you want to reject empty strings you need to add an explicit test:

if s and acceptable(s):
    print("OK")

>>>> import string
>>>> acceptable = frozenset(string.ascii_letters + "_-").issuperset
>>>> acceptable("Foo-Bar")
> True
>>>> acceptable("Foo-Bar42")
> False
>>>> acceptable("Foo Bar")
> False
>>>> acceptable(string.ascii_letters + "_-")
> True

By the way, I find that behaviour more intuitive than that of the 
str.isXXX() methods as e. g.

s.isdigit() 

will differ from

all(c.isdigit() for c in s)

for the empty string. 

What do you think, are all apples in an empty basket red or not?




More information about the Python-list mailing list