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

Python列表索引顺序异常:交替大小写功能索引跳过3问题排查

问题:文本大小写交替转换时索引异常

尝试实现文本大小写交替转换功能,但运行代码时发现索引未按0、1、2、3、4的顺序执行,跳过了索引3。相关代码如下:

sentence = input("Write a sentence")

newList = []
for i in range(len(sentence)):
    if sentence[i] != " ":
        newList.append(sentence[i])


listJoint = "".join(newList)
newList2 = []

for i in range(len(listJoint)):
    if (listJoint.index(listJoint[i]) % 2) == 0:
        print(listJoint.index(listJoint[i]))
        newList2.append(listJoint[i].upper())
    elif (listJoint.index(listJoint[i]) % 2) != 0:
        print(listJoint.index(listJoint[i]))
        newList2.append(listJoint[i].lower())

print(newList2)

#newListJoint = "".join(newList2)
#print(newListJoint[::-1])

错误原因

问题出在listJoint.index(listJoint[i])这个方法上:

  • str.index()返回的是字符串中第一个与目标字符匹配的索引,而非当前循环变量i对应的真实索引
  • 举个例子:如果listJoint是"abcbc",当循环到i=3时,字符是b,index()会返回第一个b的索引1,而非当前位置的3,这就导致了索引顺序混乱、跳值的现象

修正方案

直接用循环变量i判断奇偶,它才是当前字符的真实索引:

sentence = input("Write a sentence")

# 去除空格
newList = [char for char in sentence if char != " "]
listJoint = "".join(newList)
newList2 = []

for i in range(len(listJoint)):
    print(i)  # 现在会按0、1、2、3、4...顺序输出
    if i % 2 == 0:
        newList2.append(listJoint[i].upper())
    else:
        newList2.append(listJoint[i].lower())

print(newList2)
# newListJoint = "".join(newList2)
# print(newListJoint[::-1])

也可以用列表推导式简化代码,更简洁高效:

sentence = input("Write a sentence")
# 去除空格并完成大小写交替转换
result = "".join([
    char.upper() if idx % 2 == 0 else char.lower()
    for idx, char in enumerate(sentence)
    if char != " "
])
print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:56:29