views:

165

answers:

4

For example...

s = 'The fox jumped over a big brown log.'

k = FUNCTION(s,4)

k should be... "The fox jumped over"

I can write my own function that splits on whitespace, cuts the list and then joins the list. But that is too much work.

Anyone else knows a simpler way?

+5  A: 

Something like this:

def f(s, n):
    return ' '.join(s.split()[:n])

But it is still splitting, slicing and joining...

Andrey Vlasovskikh
Your function returns ['The', 'fox', 'jumped', 'over'] not "The fox jumped over". You need to return " ".join( s.split()[:n] ) instead.
Craig Trader
@W.Craig Already fixed that.
Andrey Vlasovskikh
+1  A: 

Why do you say "that is too much work"? Too much work for you, or too much for the computer? Is that code part of some performance critical code?

Just do what works and move on to something more important.

Bryan Oakley
Why didn't you just post this as a comment? It's not really an answer...
Swingley
Because learning how to do things short is important.
TIMEX
@alex: Learning how to do things *efficiently* is important. However, this should come after **learning how to do things**. And nowhere does "short" come into it.
Greg Hewgill
+2  A: 
x = "Hello how are you?"
' '.join(x.split()[1:3])
>>> "how are"

you can then change the numbers 1 and 3 in the list to get which words you want it to return

def split_me(string, start, end, skip):
    return ' '.join(string.split()[start:end:skip])

remember lists are indexed starting at 0 and the skip is so you can skip words:

split_me("Hello how are you", 0, 3, 2)
>>> 'hello are'
Casey
@Andrey, what's wrong with the index?
Casey
Pointless `start` and `skip` arguments. Following this style you could add such arguments as `split_string`, `join_string`, etc. The problem is solved, stop coding and move on :)
Andrey Vlasovskikh
@Casey Nothing already, see my other comment.
Andrey Vlasovskikh
+1  A: 

Try something like this:

def f(s, n):
    return " ".join( s.split()[:n] )
Craig Trader