Search code examples
pythonstripwords

How to strip a string after a certain amount of words in python


I have a paragraph "Lorem ipsum foo bar foobar stuff etc"
In python, how might I strip this string after a certain amount of words say in this case 4?


Solution

  • I have two solutions.

    The first uses more memory:

    s = "Lorem ipsum foo bar foobar stuff etc"
    print ' '.join(s.split(" ")[:4])
    

    The second may be slower:

    s = "Lorem ipsum foo bar foobar stuff etc"
    start = 0
    for i in range(4): # number of words
        start = s.find(" ", start+1)
    print s[:start]