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

PythonServer Side ProgrammingProgramming

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.

## Example

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
else:
init_val += 1
return init_val

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

## Output

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

## Explanation

• 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.

Published on 20-Sep-2021 10:57:00
Advertisements