更新時間:2018年08月09日13時50分 來源:傳智播客 瀏覽次數:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
# 1.使用字符串切片 result = str [:: - 1 ] print (result) # 2.使用列表的reverse() 函數 my_list = list ( str ) my_list.reverse() result = ''.join(my_list) print (result) # 3.使用reduce() 函數 from functools import reduce result = reduce ( lambda x, y: y + x, str ) print (result) # 4.使用遞歸函數 def func(s): if len (s) < 1 : return s return func(s[ 1 :]) + s[ 0 ] result = func( str ) print (result) # 5.for循環(huán) def func(s): result = '' max_index = len (s) - 1 for index, value in enumerate (s): result + = s[max_index - index] return result result = func( str ) print (result) |