
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Length of the Last Word in a String in Python
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.
Advertisements