XP is just a number PerlMonks

### Re^2: Five Ways to Reverse a String of Words (C#, Perl 5, Perl6, Ruby, Haskell)

by webfiend (Vicar)
 on Dec 12, 2006 at 17:46 UTC ( #589339=note: print w/replies, xml ) Need Help??

TMTOWTDI even in Python, these days:

```def reverseWords(words):
return ' '.join([word for word in words.split()][::-1])

I'd probably tweak it a bit in real-world code, though. Generators and list comprehensions make me go cross-eyed sometimes.

Update: Adjusted the code to match the full goal.

• Comment on Re^2: Five Ways to Reverse a String of Words (C#, Perl 5, Perl6, Ruby, Haskell)

Replies are listed 'Best First'.
Re^3: Five Ways to Reverse a String of Words (C#, Perl 5, Perl6, Ruby, Haskell)
by ambrus (Abbot) on Dec 12, 2006 at 22:03 UTC

You don't need [word for word in ...]. That's just the same as map { \$_ } ... in perl, an identity op on lists (more or less).

```>>> def reverseWords(words):
...     return ' '.join(words.split()[::-1])
...
>>> reverseWords("  one   two three four    ")
'four three two one'
Re^3: Five Ways to Reverse a String of Words (C#, Perl 5, Perl6, Ruby, Haskell)
by Anonymous Monk on Jun 05, 2007 at 13:41 UTC
```[word for word in words.split()] ?
```def reverseWords(words):
return ' '.join(words.split()[::-1])
It is sometimes hard to not use ::-1 once learnt, but you can use reversed which makes it clearer:
```>>> def reverseWords(word):
... 	return " ".join( reversed(word.split()) )
...
>>> reverseWords("  one   two three four    ")
'four three two one'
```

Create A New User
Node Status?
node history
Node Type: note [id://589339]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2021-01-16 02:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
The STEM quote I most wish I'd made is:

Results (154 votes). Check out past polls.

Notices?