First script, please comment and advise

Pedro Graca hexkid at dodgeit.com
Thu Mar 9 15:17:06 EST 2006


Just wrote:
> In article <slrne10bpc.9pj.hexkid at ID-203069.user.individual.net>,
>  Pedro Graca <hexkid at dodgeit.com> wrote:
>
[snip: very un-pythonic code]
>
>     def curious(text):
>         """ Return the words in input text scrambled except for the
>         first and last letter. """
>         new_text = ""
>         word = ""
>         for ch in text:
>             if ch.isalpha():

Ah! shorter and clearer than my attempt.

>                 word += ch
>             else:
>                 new_text += scramble(word)
>                 word = ""
>                 new_text += ch
>         new_text += scramble(word)

Oops. I failed to test bad input :)
Thanks for the correction.

>         return new_text
>
>     def scramble(word):
>         """ scramble word """
>         from random import shuffle
>         if len(word) < 4:
>             return word
>         letters = list(word[1:-1])

list(string) transforms a string in a list ...

>         shuffle(letters)
>         return word[0] + "".join(letters) + word[-1]

... and delimiter.join(list) transforms a list in a string.

I guess I shouldn't have payed attention to the people who said "Don't
bother with the manual, just try it."

I've just downloaded "Dive Into Python" and will print and read it.


Thank you for your corrections and hints for my code.

-- 
If you're posting through Google read <http://cfaj.freeshell.org/google>



More information about the Python-list mailing list