calling upper() on a string, not working?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed May 17 02:12:23 CEST 2006


John Salerno a écrit :
> Can someone tell me what's happening here. This is my code:
>  
> PUNCT_SPACE_SET = set(string.punctuation + string.whitespace)
> 
> def filter_letters(original):
>     return ''.join(set(original) - PUNCT_SPACE_SET)
> 
> 'original' is a string. The above works as expected, but when I change 
> it to
> 
> return ''.join(set(original.upper()) - PUNCT_SPACE_SET)
> 
> it doesn't seem to work. The full code is below if it helps to understand.
> 

Don't assume str.upper() is broken !-)

In fact, your problem is that you create the translation table based on 
uppercase letters, and apply it to a non uppercased string :

> import string
> import random
> import itertools
> 
> PUNCT_SPACE_SET = set(string.punctuation + string.whitespace)
> 
> def convert_quote(quote):
>     return encrypt_quote(quote).split('|')
> 
> def encrypt_quote(original):
       # Since it's here that we define that the new letters
       # will be uppercase only, it's our responsability
       # to handle any related conditions and problems
       # The other functions shouldn't have to even know this.
       original = original.upper()
>     original_letters = filter_letters(original)
>     new_letters = list(string.ascii_uppercase)
>     while True:
>         random.shuffle(new_letters)
>         trans_letters = ''.join(new_letters)[:len(original_letters)]
>         if test_code(original_letters, trans_letters):
>             trans_table = string.maketrans(original_letters, trans_letters)
>             break
>     return original.translate(trans_table)
> 
> def filter_letters(original):
       # here, we *dont* have to do anything else than filtering
       # upper/lower case is *not* our problem.
>     return ''.join(set(original) - PUNCT_SPACE_SET)
> 
> def test_code(original_letters, trans_letters):
>     for pair in itertools.izip(original_letters, trans_letters):
>         if pair[0] == pair[1]:
>             return False
>     return True
> 
> if __name__ == '__main__':
>     print convert_quote("The past is not dead. In fact, it's not even 
> past.|William Faulkner")

["XCD ONKX AK IGX LDNL. AI WNBX, AX'K IGX DYDI ONKX.", 'UAEEANP WNREQIDS']



More information about the Python-list mailing list