我有一个简单的程序,可以输入一个单词,询问用户他们想细分的哪一部分,然后询问用什么替换它,最后打印结果。但是我需要将其转换为递归工作。
我已经在这里使用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
我们将不胜感激。
答案 0 :(得分:0)
您可以使用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)
我认为这就是您想要的,但是请注意,这不是递归。
编辑:使用具有相同停用词的递归代码版本:
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()