使用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_wordstring 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 indexi, we check the character at that position inword1. - 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
相关产品推荐
相关产品推荐

