Agile 2009 Proposal: Continuous Testing Evolved
The New Manifesto

Kata:Python:Reverse all the words in a string

s = "Theses are the words I want to reverse"

" ".join([x[::-1] for x in s.split()])

Lets take a look at this rather terse solution from the inside out.

The variable modifier in the list comp x[::-1] is probably the strangest part of this one line kata solution. The third argument in the index is the stride; That is, the number of elements to step when extracting values. A negative number indicates that you step in reverse order, so using a -3 instead of -1 would give me every third character of each reversed word.

str.split() with no arguments splits on spaces, giving us a list of words

the list comp then iterates over the words, applying our negative stride extraction trick to reverse them

Finally, str.join concatenates the words together into a single string, using the calling string as a separator. Personally, I'd expect that method to be on the list, rather than str, but so it is. 

And the result is:

'sesehT era eht sdrow I tnaw ot esrever'


Feed You can follow this conversation by subscribing to the comment feed for this post.


I misunderstood the problem statement. I thought you wanted:
" ".join(s.split()[::-1])
which returns:
"reverse to want I words the are These"

Showing that if you and I both read "reverse the words in a string" we will end up with two different answers. This is why requirements specs don't really work. ;-)

Otherwise, in true "golf" form, you can drop the [] around the list comp, turning it into a generator comprehension which works great and doesn't create a list of reversed words before moving on to the join.
" ".join(x[::-1] for x in s.split())

Generator comps are a little newer, but mighty handy. I like the "on the fly" way that the python iterators work. Not that anyone cares, but I thought I'd include that.

In the interest of disgusting ugliness:
" ".join("".join(reversed(word)) for word in sentence.split())

Using less syntax, it does more and is harder to read. Amazing. Partly because it's having to do empty-string join to get the reversed word back together, it is much worse than the more cryptic response originally given. If 'reversed(word)' didn't return a 'reversed object' but rather a reversed string/array it would be cleaner here, but worse in other contexts.

I also just realized how python can be just as ugly as other languages, if you want to make it so. :-)

The comments to this entry are closed.