Skip to content
Advertisement

I want to find the first, second, and last words in a string

Given a string, I want to write 3 separate functions:

  • first_word is to print the first word of the string
  • second_word is to print the second word of the string
  • last_word is to print the last word of the string

If the string has 2 words in total, the output from function 2 should be equal to function 3.

Example:

sentence = "once upon a time there was a programmer"

print(first_word(sentence)) # once

print(second_word(sentence)) # upon

print(last_word(sentence)) # programmer

What I tried so far:

def first_word(str):
       space = str.find(' ')
       return(str[0:space])

sentence = "once upon a time there was a programmer"
print(first_word(sentence))

Output: once

What I’m stuck on: I’m not sure how to do the second and third functions. Is there a way to have function 1 incorporated into function 2 and 3? Then the only difference between the 3 functions is that they’re different iterations of function 1. Please explain your thought process as well.

Advertisement

Answer

You can use string split method to get words from your sentence https://www.w3schools.com/python/ref_string_split.asp

#!/usr/bin/env python3
# coding=utf-8

sentence = 'once upon a time there was a programmer'


def get_words(input):
    return input.split(" ")


def first_word(data):
    words = get_words(data)
    if len(words) != 0:
        print(f"First word = {words[0]}")


def second_word(data):
    words = get_words(data)
    if len(words) > 1:
        print(f"Second word = {words[1]}")
    else:
        print("Second word = Null")


def last_word(data):
    words = get_words(data)
    if len(words) != 0:
        print(f"Last word = {words[-1]}")


if __name__ == "__main__":
    first_word(sentence)
    second_word(sentence)
    last_word(sentence)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement