python - 使用递归和用户输入在 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
帮助将不胜感激。
解决方案
您可以使用 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()
推荐阅读
- amazon-redshift - Quick Sight 在新列中按月聚合日期
- c# - 以编程方式将视图添加到 Xamarin.Android C# 中的 GridLayout
- selenium - Python - Selenium Webdriverwait NoSuchElementException 不会被 except 捕获
- c - C中的三角函数
- r - 根据条件向一列添加值
- haskell - 如何将具有多个参数的数据中的一个参数与其他数据匹配?
- bash - 1.如何使用不包括第一个的输入 2.使用grep和sed查找用户输入的模式以及如何创建下一行
- google-sheets - 如果 FILTER 的值与 Google 表格中的上述行不同,如何使用 FILTER 返回行?
- amazon-web-services - URL 中的 Amazon S3 SOAP 返回空 200
- python - 使用 To_excel 添加新列后的 Excel 空白单元格