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

编写字符串交替大写程序时遇IndexError报错求助

Fixing the IndexError in Your Alternating Case String Code

Hey there! Let's get that code working properly. The IndexError: string index out of range you're seeing is caused by a small mistake in your loop range, plus a tiny issue with your initial string value. Let's break it down step by step:

What's Going Wrong?

  1. Incorrect Loop Range: You're using range(0, lenght+1) for your loop. Since Python strings are zero-indexed (meaning the first character is at index 0, the last at len(str1)-1), when i reaches lenght (the full length of your input string), str1[i] doesn't exist—hence the index out of range error.
  2. Unwanted Leading Space: Your str2 starts with a space (" "), which will add an extra space at the beginning of your final output.
  3. Minor Typo: You wrote lenght instead of length—it's not breaking the code, but fixing it makes things more readable.

Corrected Code

Here's the fixed version with explanations:

str1 = input("Enter a string: ")
length = len(str1)  # Fixed the typo here
print("Original string =", str1, "\nOriginal string length =", length)
str2 = ""  # Initialize as empty string instead of a space
for i in range(length):  # Loop only through valid indices (0 to length-1)
    if i % 2 == 0:
        str2 += str1[i].upper()
    else:
        str2 += str1[i].lower()  # Ensures odd-indexed chars are lowercase, matching your example
print(str2)

Key Changes Made:

  • Adjusted the loop range to range(length): This keeps us within the valid index bounds of the input string
  • Removed the leading space from str2's initial value to clean up the output
  • Added .lower() to the else clause: This guarantees odd-positioned characters are lowercase, even if the input has uppercase letters, perfectly matching your school → ScHoOl example

Testing with Your Example

If you input school, the code will output ScHoOl exactly as you wanted!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:04:51