Home > Net >  Split string and only return first 5 words
Split string and only return first 5 words

Time:06-22

I am new to Python and am starting with the basics. I am trying to split a string and consequently only show the first 5 words. The current code I have written only shows the first 5 letters from all words in stead of the first words, my code is:

fruitstal = "kiwi appel peer mandarijn banaan meloen ananas mango grapefruit"
lijst=fruitstal.split()
    [print (i[:4] for i in lijst]

CodePudding user response:

We can try splitting up until the fifth occurrence of space, then splice together that resulting list by space:

fruitstal = "kiwi appel peer mandarijn banaan meloen ananas mango grapefruit"
output = ' '.join(fruitstal.split(' ', 5)[:5])
print(output)  # kiwi appel peer mandarijn banaan

CodePudding user response:

This loops through all of the fruits in the list, prints them, then stops when it has done more than 4:

    fruitstal = "kiwi appel peer             And Mandarin banaan meloen ananas mango grapefruit"
    lijst=fruitstal.split()
    a = 0
    for i in lijst:
        if a > 4:
            break
        print(i)
        a  = 1

CodePudding user response:

Just a simple split creates a list of all fruits then, select 5 first items:

fruitstal = "kiwi appel peer mandarijn banaan meloen ananas mango grapefruit"
print(fruitstal.split()[:5])
  • Related