Python reversing a string using recursion

前端 未结 6 629
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 23:34

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\".

I wrote one that do

6条回答
  •  臣服心动
    2020-12-15 00:18

    I know its too late to answer original question and there are multiple better ways which are answered here already.My answer is for documentation purpose in case if someone is trying to implement tail recursion for the string reverse.

    def tail_rev(in_string,rev_string):
        if in_string=='':
            return rev_string
        else:
            rev_string+=in_string[-1]
            return tail_rev(in_string[:-1],rev_string)
    
    in_string=input("Enter String: ")
    rev_string=tail_rev(in_string,'')
    print(f"Reverse of {in_string} is {rev_string}") 
    

提交回复
热议问题