如何用Python实现无replace/find的三参数单词替换函数
replace()/find() Got it, let's work through this problem together. You want to create a function that replaces a target word with a replacement in a sentence, without relying on Python's built-in replace() or find() methods. Here's a clear, step-by-step implementation that handles basic cases first, then an extended version for edge cases like punctuation or embedded substrings.
Basic Implementation (Space-Separated Words)
This version assumes words are separated by single spaces and no punctuation—perfect for your example use case:
def replace_word(sentence, target, replacement): new_sentence = [] current_word = "" # Iterate through each character to build words incrementally for char in sentence: if char == " ": # We've hit a space, check if the current word matches the target if current_word == target: new_sentence.append(replacement) else: new_sentence.append(current_word) # Add the space to our result new_sentence.append(char) current_word = "" else: # Keep building the current word current_word += char # Handle the final word (since the sentence might not end with a space) if current_word == target: new_sentence.append(replacement) else: new_sentence.append(current_word) # Join all parts into the final string return "".join(new_sentence)
How It Works:
- We use a list
new_sentenceto collect our result (lists are more efficient for repeated appends than strings, which are immutable in Python). current_wordtracks the word we're building character by character as we loop through the sentence.- When we hit a space, we check if
current_wordmatches the target: if yes, we add the replacement to the result; if not, we add the original word. We then resetcurrent_wordfor the next word. - After the loop ends, we have to handle the last word (since sentences don't always end with a space).
- Finally, we join the list into a single string to return.
Test It Out:
print(replace_word("The beach is beautiful", "beach", "sky")) # Output: "The sky is beautiful"
Extended Implementation (Handles Punctuation & Substrings)
If you need to avoid replacing substrings inside other words (like not replacing "beach" in "beachball") or handle punctuation (like "beach,"), this version checks word boundaries using alphanumeric checks:
def replace_word(sentence, target, replacement): new_sentence = [] target_length = len(target) index = 0 while index < len(sentence): # Check if we're at the start of a potential target word # Either we're at the start of the sentence, or the previous character isn't alphanumeric is_word_start = (index == 0) or (not sentence[index-1].isalnum()) # Check if the substring from current index matches the target if is_word_start and index + target_length <= len(sentence): if sentence[index:index+target_length] == target: # Check if we're at the end of a word (or sentence) is_word_end = (index + target_length == len(sentence)) or (not sentence[index+target_length].isalnum()) if is_word_end: # Add the replacement and skip ahead by the target's length new_sentence.append(replacement) index += target_length continue # If no match, add the current character and move to the next new_sentence.append(sentence[index]) index += 1 return "".join(new_sentence)
Example with Edge Cases:
print(replace_word("The beach, is beautiful; beachball is not beach", "beach", "sky")) # Output: "The sky, is beautiful; beachball is not sky"
This version ensures we only replace full words, even when they're adjacent to punctuation or surrounded by other text.
内容的提问来源于stack exchange,提问作者Jonathan

