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

使用for i in range语句实现无Python内置方法的字符串编辑

Alright, let's get this sorted for your assignment—you need to use a for i in range loop instead of relying on Python's built-in replace() method, right? Your current code works fine but doesn't meet that specific requirement. Here's how to rewrite it properly:

word1 = raw_input("Give me a word! ")
letter1 = raw_input("Give me a letter! ")

# Set up an empty string to build our filtered word
modified_word = ""

# Loop through each index of the original word using range()
for i in range(len(word1)):
    # Keep the character if it's not the one we want to remove
    if word1[i] != letter1:
        modified_word += word1[i]

# Check if the target letter was present at all
if letter1 not in word1:
    print("There is no letters to replace in", word1)
else:
    print(modified_word)

Quick breakdown of the code:

  • We still collect the user's input word and target letter just like your original code did.
  • The empty modified_word string acts as a container to build our final result—we'll only add characters that aren't the one we're removing.
  • The for i in range(len(word1)) line is the core of what your assignment asks for: it iterates over every index number of the input word. For each index i, we check the character at that position in word1.
  • If the character doesn't match our target letter, we append it to modified_word.
  • Finally, we check if the target letter existed in the original word. If it didn't, we print a message letting the user know; if it did, we output our cleaned-up word.

This version sticks strictly to using a for i in range loop and avoids the built-in replace() method, while delivering the exact functionality you need.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:10:12