- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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))
The string is : Hi how are you Will The length of the last word is : 4
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.
- PHP program to find the length of the last word in the string
- Length of Last Word in C++
- Find the first maximum length even word from a string in C++
- Find the first repeated word in a string in Python?
- C++ Program to Find the Length of a String
- C program to find the length of a string?
- 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)
- C# program to find the index of a word in a string
- Program to find length of longest diminishing word chain in Python?
- Program to find length longest prefix sequence of a word array in Python
- What is the max length of a Python string?