Skip to content

S2Q1 · Last Word Starting with Uppercase Letter

⚡ Quick Reference

Function: last_word_starts_with_upper_case(sentence: str)

Core idea: split into words, scan left-to-right, keep overwriting result every time a match is found. The final value is the last match.

def last_word_starts_with_upper_case(sentence: str):
    result = None
    for word in sentence.split():
        if word[0].isupper():
            result = word
    return result

Key rules: - Returns None if no uppercase-starting word exists - word[0].isupper() checks only the first character - Loop always finishes - "last wins" overwrite pattern


Problem Statement

Problem

Write a function last_word_starts_with_upper_case(sentence) that returns the last word whose first character is uppercase, or None if no such word exists.

Examples:

Input
"This is a Test sentence"
Output
"Test"
Input
"no uppercase words here"
Output
None

Tracing the example

Sentence: "This is a Test sentence"

Word word[0].isupper()? result after
"This" "This"
"is" "This"
"a" "This"
"Test" "Test"
"sentence" "Test"

Return → "Test"


Solution approaches

def last_word_starts_with_upper_case(sentence: str):
    result = None
    for word in sentence.split():
        if word[0].isupper():
            result = word
    return result
def last_word_starts_with_upper_case(sentence: str):
    matches = [w for w in sentence.split() if w[0].isupper()]
    return matches[-1] if matches else None
def last_word_starts_with_upper_case(sentence: str):
    return next(
        (w for w in reversed(sentence.split()) if w[0].isupper()),
        None
    )

next(..., None) returns the first element of the reversed generator - which is the last match in the original sentence. Short-circuits as soon as it finds one.

def last_word_starts_with_upper_case(sentence: str):
    matches = list(filter(lambda w: w[0].isupper(), sentence.split()))
    return matches[-1] if matches else None

Key takeaways

01

"Last wins" overwrite

Init to None, overwrite on every match, return after the loop finishes. The final value is always the last match - no index tracking needed.

02

word[0].isupper() checks first char only

str.isupper() on a single character tests if that character is uppercase. Calling it on the full word would require all characters to be uppercase - not what we want here.

03

next(reversed(...), None) for last match

Reversing and taking the first match is equivalent to finding the last match in the original order. next(..., None) safely returns None if no match exists.