Python使用递归反转字符串 [英] Python reversing a string using recursion
本文介绍了Python使用递归反转字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用递归来反转 python 中的字符串,以便向后显示字符(即Hello"将变为olleh"/o l l e h".
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
我写了一个迭代的:
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
n = n + 1
result = s[ start: n ] + " " + result
start = n
return result
但是我究竟如何递归地做到这一点?我对这部分感到困惑,尤其是因为我不太会使用 python 和递归.
But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much.
任何帮助将不胜感激.
推荐答案
def rreverse(s):
if s == "":
return s
else:
return rreverse(s[1:]) + s[0]
(很少有人在 Python 中进行繁重的递归处理,语言 不是为它设计的.)
(Very few people do heavy recursive processing in Python, the language wasn't designed for it.)
这篇关于Python使用递归反转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文