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

Python字符串首尾字符相同计数错误排查:结果应为3却输出0

问题分析与解决

你的代码运行结果为0的核心原因是Python字符串比较区分大小写:

  • 列表里的"Ana"首字符是大写A,尾字符是小写a,两者不相等
  • "Bob"首字符B和尾字符b同理,大小写不同导致比较失败
  • "Alexandra"首字符A和尾字符a也是同样的问题

原本你认为符合条件的3个单词,在区分大小写的比较下都不满足,最终统计结果为0。

要解决这个问题,只需要在比较首尾字符时统一大小写(转成小写或大写都可以),修正后的代码如下:

strings = ["Ana", "Alice", "Bob", "Alex", "Alexandra"]

count = 0 

for word in strings:
    # 统一转成小写后比较
    if word[0].lower() == word[-1].lower():
        count += 1

print(count)  # 输出3

或者也可以统一转成大写:

strings = ["Ana", "Alice", "Bob", "Alex", "Alexandra"]

count = 0 

for word in strings:
    if word[0].upper() == word[-1].upper():
        count += 1

print(count)  # 输出3

内容的提问来源于stack exchange,提问作者Aleksandra Milicevic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 12:40:54