首页 > 解决方案 > 使用递归和用户输入在 Python 中进行简单的搜索和替换

问题描述

我有一个简单的程序,它输入一个单词,询问用户他们想要子串出哪个部分,然后询问用什么替换它,最后打印结果。但我需要将其转换为递归工作。

我在这里用 Python 从基本意义上创建了它。

word = input("Enter a word: ")
substring = input("Please enter the substring you wish to find: ")
new_entry = input("Please enter a string to replace the given substring: ")
new_word = word.replace(substring, new_entry)
print("Your new string is: " + new_word)

它应该递归工作并显示如下:

Enter a word: world
Please enter the substring you wish to find: or
Please enter a string to replace the given substring PP
Your new string: is wPPld 

帮助将不胜感激。

标签: pythonrecursioninputreplacesubstring

解决方案


您可以使用 while 循环,但您需要定义一个停用词才能有出路。在此示例中,我将停用词定义为 quit:

word = ''
while (word != 'quit'):
    word = input("Enter a word: ")
    substring = input("Please enter the substring you wish to find: ")
    new_entry = input("Please enter a string to replace the given substring: ")
    new_word = word.replace(substring, new_entry)
    print("Your new string is: " + new_word)

我认为这就是你想要的,但请注意这不是 recursion

编辑:使用具有相同停用词的递归的代码版本:

def str_replace_interface():
    word = input("Enter a word: ")
    if word != 'quit':
        substring = input("Please enter the substring you wish to find: ")
        new_entry = input("Please enter a string to replace the given substring: ")
        new_word = word.replace(substring, new_entry)
        print("Your new string is: " + new_word)
        str_replace_interface()

str_replace_interface()

推荐阅读