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
How to Print the Last Word in a sentence using Python?
Extracting the last word from a sentence is a common text processing task in Python. This can be accomplished using the split() method to break the sentence into words and accessing the last element.
Using split() Method
The split() method divides a string into a list of words, making it easy to access the last word using negative indexing.
Syntax
string.split(separator, maxsplit)
Parameters:
separator Optional. Specifies the delimiter (default is whitespace)
maxsplit Optional. Maximum number of splits (default is -1 for all occurrences)
Example
def print_last_word(sentence):
# Split the sentence into words
words = sentence.split()
# Get the last word using negative indexing
last_word = words[-1]
# Print the last word
print("Last word:", last_word)
# Example usage
sentence = "Python is a powerful programming language"
print_last_word(sentence)
# Another example
sentence2 = "TutorialsPoint provides excellent tutorials"
print_last_word(sentence2)
Last word: language Last word: tutorials
Using rsplit() for Efficiency
For large sentences, rsplit() with maxsplit=1 is more efficient as it only splits from the right once ?
def get_last_word_efficient(sentence):
# Split from right, only once
parts = sentence.rsplit(' ', 1)
return parts[-1] if parts else ""
sentence = "This is a very long sentence with many words"
last_word = get_last_word_efficient(sentence)
print("Last word:", last_word)
Last word: words
Handling Edge Cases
Consider scenarios with empty strings, single words, or extra whitespace ?
def robust_last_word(sentence):
# Strip whitespace and check if empty
sentence = sentence.strip()
if not sentence:
return "No words found"
words = sentence.split()
return words[-1]
# Test edge cases
test_cases = [
"Single",
"Multiple words here",
" Extra spaces ",
"",
" "
]
for test in test_cases:
result = robust_last_word(test)
print(f"'{test}' ? {result}")
'Single' ? Single 'Multiple words here' ? here ' Extra spaces ' ? spaces '' ? No words found ' ' ? No words found
Comparison of Methods
| Method | Performance | Best For |
|---|---|---|
split()[-1] |
Good for short text | Simple cases |
rsplit(' ', 1)[-1] |
Better for long text | Large sentences |
| Regular expressions | Slower but flexible | Complex patterns |
Common Use Cases
Extracting the last word is useful in various applications:
Text Processing Analyzing file extensions, usernames, or domain names
Natural Language Processing Sentiment analysis and keyword extraction
Data Validation Checking format compliance in user inputs
Log Analysis Extracting status codes or error types from log entries
Conclusion
Use split()[-1] for simple last word extraction. For better performance with large text, use rsplit(' ', 1)[-1]. Always handle edge cases like empty strings for robust applications.
