Python 使用递归删除字符串中的空格
2-3个小时前我参加了考试。我们的老师要求我们: 1) 从用户处获取一个字符串句子 2) 将字符串发送到函数 3) 我们的任务是删除空格,但不能使用字符串函数,必须使用递归 怎么了Python 使用递归删除字符串中的空格,python,function,recursion,Python,Function,Recursion,2-3个小时前我参加了考试。我们的老师要求我们: 1) 从用户处获取一个字符串句子 2) 将字符串发送到函数 3) 我们的任务是删除空格,但不能使用字符串函数,必须使用递归 怎么了 def deletespace(name): if(len(name)==0): return "" else: str="" if(ord[name[0]])>chr(65) and ord(name[0])<chr(122):
def deletespace(name):
if(len(name)==0):
return ""
else:
str=""
if(ord[name[0]])>chr(65) and ord(name[0])<chr(122):
return str+deletespace(name[1:])
name=input("Please enter the name..")
deletespace(name)
def deletespace(名称):
如果(len(name)==0):
返回“”
其他:
str=“”
if(ord[name[0]]>chr(65)和ord(name[0])缺少第二个if
的else
子句。在这种情况下,您会返回什么?测试可能已经结束,但您仍然可以从以下示例中学习一些东西:
>>> def del_char(text, char=' '):
head, *tail = text
return ('' if head == char else head) + \
(del_char(tail, char) if tail else '')
>>> def main():
name = input('Please enter your name: ')
spaceless = del_char(name)
print(spaceless)
>>> main()
Please enter your name: Arda Zaman
ArdaZaman
>>>
如果您想要一个功能更强大的del_char
函数版本,请尝试此str_replace
函数,它可以完成与第一个函数相同的功能,但具有扩展功能:
def str_replace(string, old=' ', new='', count=0):
head, tail = string[0], string[1:]
if head == old:
head, count = new, count - 1
if not count:
return head + tail
return head + str_replace(tail, old, new, count) if tail else head
我发现有两个问题:
1) 。在第6行中,您试图访问ord的索引,if(ord[name[0]])>chr(65)和ord(name[0])chr(65)以及ord(name[0])1。您每次都通过递归重新初始化变量
2) 您永远不会增加您的返回值
尝试更类似于:
def removespace(str):
if len(str) == 0 : return ""
if str[0] == " ":
return removespace(str[1:])
else :
return str[0] + removespace(str[1:])
这将依次将每个字符添加到返回值中,跳过它找到的任何空格字符。这还将删除“:”和“/”,并在其中添加任何您想要的内容
def removewhite(string):
if len(string) == 0:
return ""
if string[0] in " :/":
return removewhite(string[1:])
else:
return string[0] + removewhite(string[1:])
string = "abcd , : def"