Length of the last word

EasyFunction Programs · 36 of 39

Write a Python function that returns the length of the last word in a string.

Advertisement
Input
"Learning Python is fun   "
Output
3 0

Approach

  1. split() ignores trailing spaces.

Solution

Python
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
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs