Help with code-lists and strings

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jan 5 23:19:04 EST 2011


Apologies if this comes through twice, I'm having problems with my news 
client and/or provider.


On Wed, 05 Jan 2011 16:56:40 -0600, GrayShark wrote:

> In python it's best to build up you functional needs. So two steps.
> First a nand (negative 'and' operation). Then wrap that with a function
> to create two strings of your list element, you''re calling 'word'. By
> the way, list is reserved word, like string. Don't get in the bad habit
> of using it.


Speaking of bad habits:

> def nand( a, b ):
> 	"""nand has to vars. Both must be strings """ 
>       return( ( not eval( a ) ) and ( not eval( b ) ) )


What is the purpose of the two calls to eval, other than potentially 
introducing serious security bugs, being slow, and raising exceptions?


def nand(a, b):
    return not (a and b)


is faster and safer, and less likely to cause annoyance if somebody 
manages to fool you into executing something similar to:

nand("0", "__import__('os').system('# r m -rf /')")


More safely, and works on both Linux and Windows:

nand("0", "__import__('os').system('dir .')")



> Eval of 'Abcd'.isupper() returns False. Ditto 'Abcd'.islower(); negate
> both results, 'and' values, return.
> 
> Now wrap 'nand' in packaging an you're cooking with grease.

Eww. Greasy food.

I think the idiom you are thinking of is "now you're cooking with gas", 
gas cooking being cleaner, faster and easier than cooking with wood.


> def mixed_case( str ):
> 	return nand( "'%s'.islower()" % str , "'%s'.isupper()" % str )

I'm afraid that's incorrect, because it returns True for strings that 
aren't mixed case:

>>> mixed_case("123")
True

as well as strings that can't be mixed anything on account of being a 
single character:

>>> mixed_case("!")
True


A better solution would be:


def ismixed(s):
    seen_upper = seen_lower = False
    for c in s:
        if c.isupper(): seen_upper = True
        if c.islower(): seen_lower = True
        if seen_upper and seen_lower:
            return True
    return False


which should return True if and only if the string contains both 
lowercase and uppercase characters.




-- 
Steven



More information about the Python-list mailing list