
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
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.
- Related Articles
- PHP program to find the length of the last word in the string
- Length of Last Word in C++
- Finding the length of second last word in a sentence in JavaScript
- Function to find the length of the second smallest word in a string in JavaScript
- Find First and Last Word of a File Containing String in Java
- Find the first maximum length even word from a string in C++
- Find the first repeated word in a string in Python?
- Find frequency of each word in a string in Python
- Find the first repeated word in a string in Python using Dictionary
- Find length of a string in python (3 ways)
- Program to find length longest prefix sequence of a word array in Python
- Program to find length of longest diminishing word chain in Python?
- C# program to find the index of a word in a string
- Python – Word Frequency in a String
- Find the first repeated word in a string in Java

Advertisements