Skip to content

S1Q2 · Check for Greeting Prefix

⚡ Quick Reference

Function: starts_with_greeting(s: str) -> bool

Core idea: check if the string starts with "Hello " or "Hi " (space included).

def starts_with_greeting(s):
    return s.startswith("Hello ") or s.startswith("Hi ")

Key rules: - The space after the greeting is mandatory - "HelloWorld" is False - Case-sensitive - "hello World" would be False - str.startswith() accepts a tuple to check multiple prefixes at once


Problem Statement

Problem

Write a function starts_with_greeting(s) that returns True if s starts with "Hello " or "Hi " (including the trailing space).

Examples:

Input
"Hello World"
Output
True
Input
"Hi There"
Output
True
Input
"HelloWorld"
Output
False
Input
"Greetings Earthling"
Output
False

Tracing all examples

Input startswith("Hello ") startswith("Hi ") Result
"Hello World" True
"Hi There" True
"Greetings Earthling" False
"HelloWorld" ❌ (no space) False
"HiThere" ❌ (no space) False

Solution approaches

def starts_with_greeting(s):
    return s.startswith(("Hello ", "Hi "))

str.startswith() accepts a tuple of prefixes - returns True if the string starts with any of them. The cleanest single-expression solution.

def starts_with_greeting(s):
    return s.startswith("Hello ") or s.startswith("Hi ")
starts_with_greeting = lambda s: s.startswith(("Hello ", "Hi "))

Key takeaways

01

The space is part of the prefix

"Hello " includes a trailing space - this ensures "HelloWorld" correctly returns False. Without the space, any string starting with "Hello" would match.

02

startswith() accepts a tuple

s.startswith(("Hello ", "Hi ")) checks both prefixes in one call - cleaner than two separate startswith() calls joined with or. The same trick works with endswith().

03

Case-sensitive by design

startswith() is case-sensitive. "hello World" and "HI there" would both return False. The problem doesn't ask for case-insensitive matching, so no .lower() needed.