Simon Solnes
Simon Solnes

Reputation: 61

Detecting whether a string contains non-letters

How can I write a function that detects whether a string has non-letter characters in it?

Something like:

def detection(a):
    if !"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" in a:
        return True
    else:
        return False
print detection("blablabla.bla")

Upvotes: 0

Views: 420

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 121976

The approach your pseudocode attempts could be written as follows:

from string import ascii_letters

def detection(s, valid=set(ascii_letters)):
    """Whether or not s contains only characters in valid."""
    return all(c in valid for c in s)

This uses string.ascii_letters to define valid characters (rather than write out your own string literal), a set to provide efficient (O(1)) membership testing and all with a generator expression to evaluate all characters c in the string s.

Given that str.isalpha already exists, though, this is reinventing the wheel.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121524

Use the str.isalpha() method; it only returns True if all characters in a string are letters. Negate the result with not; if object.isalpha() returns True (only letters in the string) then not object.isalpha() returns False, and vice versa:

def detection(string):
    return not string.isalpha()

Demo:

>>> def detection(string):
...     return not string.isalpha()
... 
>>> detection('jfiopafbjk')
False
>>> detection('42jfiopafbjk')
True
>>> detection('jfiopafbjk42')
True
>>> detection('jfiop42afbjk')
True

Upvotes: 4

Related Questions