Python exercise 022: Use recursive functions to reverse the string, python022
[Python exercise 022]The input five characters are printed in reverse order using the recursive function call method.
---------------------------------------
Another recursive question! However, with the experience of [Python exercise question 021: Recursive Method for factorial], it is not difficult to draw a factorial Based on Huludao. The Code is as follows:
Str = input ('enter several characters: ') def f (x): if x =-1: return ''else: return str [x] + f (x-1) print (f (len (str)-1 ))
The output result is as follows:
Enter several characters: abcdefg
Gfedcba
What if recursive functions are not required? It's much simpler: first convert the input string into a list, sort it in reverse order, and then join () together to bring it to the table. The Code is as follows:
Str = list (input ('enter several characters: ') str. reverse () print (''. join (str ))
It may be that my current level is too low to understand the power of recursive functions. A long journey ......
++
Source: getting started with programming languages: 100 typical examples [Python]