Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Find the length of the last word in a string
Finding the length of the last word in a string is a common string manipulation task in Python. There are several approaches to solve this problem, from custom iteration to using built-in string methods.
Method 1: Using Custom Iteration
This approach removes extra spaces and iterates through the string to count characters of the last word ?
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
Method 2: Using split() Method
A simpler approach using Python's built-in string methods ?
def last_word_length_simple(text):
words = text.strip().split()
return len(words[-1]) if words else 0
# Test with different examples
test_strings = ["Hi how are you Will", " Python ", "SingleWord", ""]
for text in test_strings:
length = last_word_length_simple(text)
print(f"'{text}' ? Last word length: {length}")
'Hi how are you Will' ? Last word length: 4 ' Python ' ? Last word length: 6 'SingleWord' ? Last word length: 10 '' ? Last word length: 0
Method 3: Backward Iteration
Starting from the end of the string and counting backwards until a space is found ?
def last_word_length_backward(text):
text = text.strip()
if not text:
return 0
length = 0
for i in range(len(text) - 1, -1, -1):
if text[i] == ' ':
break
length += 1
return length
test_string = "Hello world Python"
result = last_word_length_backward(test_string)
print(f"String: '{test_string}'")
print(f"Last word length: {result}")
String: 'Hello world Python' Last word length: 6
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Custom Iteration | O(n) | O(1) | Understanding the logic |
| split() Method | O(n) | O(n) | Simplicity and readability |
| Backward Iteration | O(k) | O(1) | Efficiency (k = last word length) |
How It Works
The custom iteration method strips extra spaces and resets the counter when encountering a space
The split() method divides the string into words and returns the length of the last element
Backward iteration starts from the end and counts characters until hitting a space
All methods handle edge cases like empty strings and extra whitespace
Conclusion
Use the split() method for simplicity and readability. Choose backward iteration for better efficiency when dealing with long strings. The custom iteration approach helps understand the underlying logic of string processing.
