Python - Find the length of the last word in a string

When it is required to find the length of the last word in a string, a method is defined that removes the extra empty spaces in a string, and iterates through the string. It iterates until the last word has been found. Then, its length is found and returned as output.


Below is a demonstration of the same

def last_word_length(my_string):
   init_val = 0

   processed_str = my_string.strip()

   for i in range(len(processed_str)):
      if processed_str[i] == " ":
         init_val = 0
         init_val += 1
   return init_val

my_input = "Hi how are you Will"
print("The string is :")
print("The length of the last word is :")


The string is :
Hi how are you Will
The length of the last word is :


  • A method named ‘last_word_length’ is defined that takes a string as a parameter.

  • It initializes a value to 0.

  • The string is stripped of extra spaces, and is iterated over.

  • When an empty space is encountered, the value is kept as 0, otherwise it is incremented by 1.

  • Outside the method, a string is defined and is displayed on the console.

  • The method is called by passing this string as a parameter.

  • The output is displayed on the console.

Updated on: 20-Sep-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started