You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中first_and_last函数处理空字符串时触发IndexError的问题排查

Why You're Getting That IndexError with Empty Strings

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 message is empty, len(message) == 0 is True — the function returns True immediately, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 07:22:32