s = "Theses are the words I want to reverse"
" ".join([x[::-1] for x in s.split()])
« Agile 2009 Proposal: Continuous Testing Evolved | Main | The New Manifesto »
TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00e54fb013da883401116848e45c970c
Listed below are links to weblogs that reference Kata:Python:Reverse all the words in a string:
You can follow this conversation by subscribing to the comment feed for this post.
This is only a preview. Your comment has not yet been posted.
As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.
Having trouble reading this image? View an alternate.
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. :-)
Posted by: Tim | July 28, 2009 at 10:25 PM