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).
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:
"Hello World"
True
"Hi There"
True
"HelloWorld"
False
"Greetings Earthling"
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¶
str.startswith() accepts a tuple of prefixes - returns True if the string starts with any of them. The cleanest single-expression solution.
Key takeaways¶
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.
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().
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.