Home > Software design >  I want to find the first, second, and last words in a string
I want to find the first, second, and last words in a string

Time:08-10

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.

CodePudding user response:

You can form a list of all the strings in the given sentence and the use the corresponding indices to get the word you want as demonstrated below

class Word_Finder:
    def __init__(self,sentence):
        self.sentence = sentence 
        self.word_list = self.sentence.split() #splits the sentence 

    def first_word(self):
        return self.word_list[0]
    def second_word(self):
        return self.word_list[1]
    def last_word(self):
        return self.word_list[-1]

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

words = Word_Finder(sentence)

print(words.first_word())
print(words.second_word())
print(words.last_word())

Here , I am assuming that your sentence will always have 2 or more words.

CodePudding user response:

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)

CodePudding user response:

use :

def finder(str, value):
    space = str.split(' ')
    if value == "first":
        return space[0]
    elif value == "second":
        return space[1]
    elif value == "last":
        return space[-1]

sentence = "once upon a time there was a programmer"
print(finder(sentence, "first"))
print(finder(sentence, "second"))
print(finder(sentence, "last"))

CodePudding user response:

To lessen the bloat of using def functions, we could use a simple lambda function that uses the split() operation.

This may look something like this:

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

find_word = lambda index: sentence.split(" ")[index]

find_word can now be given any arbitrary index to list any word you may want.

find_word(0)  # returns 'once'
find_word(1)  # returns 'upon'
find_word(-1) # returns 'programmer'

A def function implementation would be:

def find_word(sentence, index) -> String:
    # except when index is outside of sentence length
    try:
        return sentence.split(" ")[index]
    except IndexError:
        return ""
    
  • Related