Detec nonascii in a string

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Feb 23 10:57:29 EST 2006


On Thu, 23 Feb 2006 12:32:35 -0300, Sebastian Bassi wrote:

> Hello,
> 
> How do I detect non-ascii letters in a string?
> I want to detect the condition that a string have a letter that is not
> here: string.ascii_letters

for c in some_string:
    if c not in string.ascii_letters:
        raise ValueError("Non-ascii value!!!")

Instead of raising an error, you can take whatever action you prefer:

for c in some_string:
    if c not in string.ascii_letters:
        print "Character '%s' is non-ascii." % repr(c)

Or turn it into a function:

def isascii(s):
    for c in some_string:
        if c not in string.ascii_letters:
            return False
    return True
    

-- 
Steven.




More information about the Python-list mailing list