Reverse a string using recursion

June 12, 2008 – 1:52 am

Very basic – take a string and reverse it using simple recursion. I’m sure there’s a bunch of ways to do it, but like the fibonacci you should aim to be able to code something like the below in about 20 seconds…

>>> def reverse(str):
    if len(str)==1:
        return str
    else:
        return reverse(str[1:])+str[0]

>>> reverse('hello')
'olleh'
>>>

Without using recursion, the simplest way to reverse a string is to use the slice function:

>>> 'abcdef'[::-1]
'fedcba'
>>>

Post a Comment