Saturday, November 16, 2024
Google search engine
HomeLanguagesPython – Print the last word in a sentence

Python – Print the last word in a sentence

Given a string, the task is to write a Python program to print the last word in that string.

Examples:

Input: sky is blue in color

Output: color

Explanation: color is last word in the sentence.

Input: Learn algorithms at neveropen

Output: neveropen

Explanation: neveropen is last word in the sentence.

Approach #1: Using For loop + String Concatenation

  • Scan the sentence
  • Take an empty string, newstring.
  • Traverse the string in reverse order and add character to newstring using string concatenation.
  • Break the loop till we get first space character.
  • Reverse newstring and return it (it is the last word in the sentence).

Below is the implementation of the above approach:

Python3




# Function which returns last word
def lastWord(string):
   
    # taking empty string
    newstring = ""
     
    # calculating length of string
    length = len(string)
     
    # traversing from last
    for i in range(length-1, 0, -1):
       
        # if space is occurred then return
        if(string[i] == " "):
           
            # return reverse of newstring
            return newstring[::-1]
        else:
            newstring = newstring + string[i]
 
 
# Driver code
string = "Learn algorithms at neveropen"
print(lastWord(string))


Output:

neveropen

Approach #2: Using split() method

  • As all the words in a sentence are separated by spaces.
  • We have to split the sentence by spaces using split().
  • We split all the words by spaces and store them in a list.
  • The last element in the list is the answer

Below is the implementation of the above approach:

Python3




# Function which returns last word
def lastWord(string):
   
    # split by space and converting
    # string to list and
    lis = list(string.split(" "))
     
    # length of list
    length = len(lis)
     
    # returning last element in list
    return lis[length-1]
 
 
# Driver code
string = "Learn algorithms at neveropen"
print(lastWord(string))


Output:

neveropen

The time and space complexity for all the methods are the same:

Time Complexity: O(n)

Auxiliary Space: O(n)

Approach #3: Using rfind() method

In this approach, we use the rfind() method to find the index of the last space in the string.
The part of the string from the last space to the end of the string is the last word.
Below is the implementation of the above approach:

Python3




#Function which returns last word
def lastWord(string):
  # finding the index of last space
  index = string.rfind(" ")
 
  # last word
  return string[index+1:]
#Driver code
string = "Learn algorithms at neveropen"
print(lastWord(string))
#This code is contributed by Edula Vinay Kumar Reddy


Output

neveropen

Time Complexity: O(n)

Auxiliary Space: O(1)

Approach #4: Using reversed() function:

Algorithm:

  1. Reverse the given string.
  2. Find the index of the first space in the reversed string.
  3. Return the last word in the original string by taking a slice from the original string starting from the end of the
  4. reversed string to the position of the first space in the reversed string.

Python3




# Function to find the last word of a string
def lastWord(string):
    # reversing the string
    reversed_string = string[::-1]
    # finding the index of first space in reversed string
    index = reversed_string.find(" ")
    # returning the last word in original string
    return string[-index-1:]
# Driver code
string = "Learn algorithms at neveropen"
print(lastWord(string)) 
#This code is contributed by Jyothi Pinjala.


Output

 neveropen

Time Complexity:
The time complexity of the find() function used in the implementation is O(n), where n is the length of the string. The slicing operation in Python also takes O(n) time complexity. Therefore, the overall time complexity of this algorithm is O(n).

Space Complexity:
The space complexity of this algorithm is O(n), where n is the length of the string. This is because we are creating a new string object by reversing the original string. However, the space complexity can be further optimized by iterating over the string from the end to find the last word instead of reversing the entire string

RELATED ARTICLES

Most Popular

Recent Comments