invert or reverse a string... warning this is a rant

Tim Chase python.list at tim.thechases.com
Thu Oct 19 19:30:04 CEST 2006


> P.S.  How about a string.shuffle() method that splits the string in half
> into two new strings str1 and str2, and then recompiles the string by
> alternating one character from each str1 and str2 as it goes?  Like
> shuffling cards.  ;)

Well, for a true shuffling of a string, there's a 
random.shuffle() but it chokes on strings.  You have to do a 
little song-and-dance to get a shuffled string:

 >>> import random
 >>> s = "hello world?"
 >>> a = list(s)
 >>> random.shuffle(a)
 >>> s2 = ''.join(a)
 >>> s2
'wlhlldor oe?'

Not quite the same algorithm you used.  That would be something like

 >>> "".join(sum(map(list,zip(s,s[len(s)/2:])),[]))

(my first attempt:

 >>> "".join(sum(map(list,zip(s[0:len(s)/2],s[len(s)/2:])),[]))

had problems when the list didn't contain an even number of chars)

-tkc







More information about the Python-list mailing list