w3resource logo


Python Exercises

Python Challenges: Find the length of the last word

Python Challenges - 1: Exercise-30 with Solution

Write a Python program to find the length of the last word.

Input : Python Exercises
Output : 9

Explanation :

Python: Find the length of the last word

Sample Solution :-

Python Code :

def length_of_last_word(s):
        words = s.split()
        if len(words) == 0:
            return 0
        return len(words[-1])

print(length_of_last_word("Python Exercises"))
print(length_of_last_word("Python"))
print(length_of_last_word(""))
print(length_of_last_word("  "))

Output :

9                                                                       
6                                                                       
0                                                                       
0 

Flowchart:

Python Flowchart: Find the length of the last word

Python Code Editor:

def length_of_last_word(s):
        words = s.split()
        if len(words) == 0:
            return 0
        return len(words[-1])

print(length_of_last_word("Python Exercises"))
print(length_of_last_word("Python"))
print(length_of_last_word(""))
print(length_of_last_word("  "))

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program