Python Practice › Function Programs › Program 36
Length of the last word
Write a Python function that returns the length of the last word in a string.
Input
"Learning Python is fun "
Output
3 0
Approach
split()ignores trailing spaces.
Solution
def last_word_length(text): words = text.split() return len(words[-1]) if words else 0 print(last_word_length("Learning Python is fun "), last_word_length(" "))Output
3 0
Learn the concept
New to this topic? Read the lesson, then come back.