Open In App

Python – Print the last word in a sentence

Improve
Improve
Like Article
Like
Save
Share
Report

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 geeksforgeeks

Output: geeksforgeeks

Explanation: geeksforgeeks 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 geeksforgeeks"
print(lastWord(string))

Output:

geeksforgeeks


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 geeksforgeeks"
print(lastWord(string))

Output:

geeksforgeeks


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 geeksforgeeks"
print(lastWord(string))
#This code is contributed by Edula Vinay Kumar Reddy

Output
geeksforgeeks


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 geeksforgeeks"
print(lastWord(string))  
#This code is contributed by Jyothi Pinjala.

Output
 geeksforgeeks



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

Approach 5: Using re (Regular Expression)

  • Import the re module.
  • Define the find_last_word_v4 function.
  • Use re.search(r’\b\w+\b’, sentence[::-1]) to search for a whole word in the reversed sentence.
  • Check if a match is found (if match:).
  • If there’s a match, return the reversed group (match.group()[::-1]), representing the last word.
  • If no match is found, return None.
Python3
import re

def find_last_word_v4(sentence):
    # Step 1: Use regular expression to search for a whole word in the reversed sentence
    match = re.search(r'\b\w+\b', sentence[::-1])

    # Step 2: Check if a match is found
    if match:
        # Step 3: Return the reversed group, representing the last word
        return match.group()[::-1]
    else:
        # Step 4: If no match is found, return None
        return None

# Example 1
input1 = "sky is blue in color"
output1 = find_last_word_v4(input1)
print(output1)

# Example 2
input2 = "Learn algorithms at geeksforgeeks"
output2 = find_last_word_v4(input2)
print(output2)

Output
color
geeksforgeeks

Time Complexity:

The time complexity is O(N), where N is the length of the input sentence. The regular expression search and the slicing operations are linear with respect to the length of the sentence.

Space Complexity:

The space complexity is O(1) because the function uses a constant amount of space regardless of the input size. The space used is for variables like match and temporary storage during the slicing operations, which do not depend on the length of the sentence.



Last Updated : 18 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads