Facebook
From a, 1 Year ago, written in Python.
Embed
Download Paste or View Raw
Hits: 128
  1. # Write your solution here
  2.  
  3. def first_word(word1: str):
  4. # 1.Finding the first word in a sentence
  5.  
  6.     word_start = 0
  7.     word_end = word1.find(" ")
  8.     word1 = word1[word_start:word_end]
  9.     return word1
  10.  
  11. def second_word(word2: str):
  12.  
  13. # Check the sentence if its only of two words and return second word
  14.     two_words = ""
  15.    
  16.     if word2.count(" ") == 1:
  17.         two_words = word2.find(" ")
  18.         word2 = word2[two_words +1::]
  19.  
  20.         return word2
  21.  
  22. # Return the second word of a sentence
  23.     start_word2 = first_word(word2) # Once
  24.     word2_start = len(start_word2) + 1
  25.     word2_end = 0
  26.  
  27.     i = len(start_word2) + 1
  28.  
  29.     while i < len(word2):
  30.         if word2[i] == " ":
  31.             word2_end = i
  32.             break
  33.         i += 1
  34.            
  35.        
  36.     word2 = word2[len(start_word2) + 1:word2_end]
  37.     return word2
  38.  
  39. def last_word(word3: str):
  40.  
  41. # Finding the last word of a sentence with for loop using negative itteration  
  42.     last_word = ""
  43.    
  44.     for i in range(len(word3)- 1, -1, -1):
  45.         if word3[i] == " ":
  46.             last_word = word3[i + 1:]
  47.             break
  48.  
  49.     return last_word
  50.            
  51.  
  52. # You can test your function by calling it within the following block
  53.  
  54.  
  55. if __name__ == "__main__":
  56.     sentence = "once upon a time there was a programmer"
  57.     print(first_word(sentence))
  58.     print(second_word(sentence))
  59.     print(last_word(sentence))

Replies to first, second, last rss

Title Name Language When
Re: first, second and last word Sweltering Stork python 1 Year ago.