Python中first_and_last函数处理空字符串时触发IndexError的问题排查
Hey Annie, let's break down exactly what's causing that error in your first_and_last function and how to fix it.
The Root of the Problem
The issue boils down to the order of your conditions in the if statement. Let's look at your original code line:
if message[0] == message[-1] or len(message) == 0:
Python uses "short-circuit evaluation" for the or operator — it checks the left-hand condition first, and only moves to the right one if the left is false. When you pass an empty string (""), Python tries to evaluate message[0] first. But an empty string has no characters at all, so accessing index 0 (or -1) triggers an IndexError before it ever gets to check if len(message) == 0.
(Side note: I noticed your error message mentions message[1] instead of message[-1] — that's probably a typo when you wrote up your question, but the core issue is the same: trying to access an index that doesn't exist in an empty string.)
The Simple Fix
All you need to do is reverse the order of your conditions. Check if the string is empty first, so Python skips the index access entirely when dealing with empty strings:
def first_and_last(message): if len(message) == 0 or message[0] == message[-1]: return True else: return False
Here's how this works:
- If
messageis empty,len(message) == 0isTrue— the function returnsTrueimmediately, never trying to access any string indices. - For non-empty strings, we safely check if the first and last characters match.
Testing the Fixed Code
Let's run your test cases with the corrected function:
print(first_and_last("else")) # Returns True (first 'e' matches last 'e') print(first_and_last("tree")) # Returns False (first 't' doesn't match last 'e') print(first_and_last("")) # Returns True with no error!
Bonus: A More Concise Version
If you want to simplify the code even further, you can return the boolean result directly without an if/else block:
def first_and_last(message): return len(message) == 0 or message[0] == message[-1]
This works because the or expression evaluates to a boolean value, which we can return immediately.
内容的提问来源于stack exchange,提问作者Annie

