教育行業(yè)A股IPO第一股(股票代碼 003032)

全國(guó)咨詢/投訴熱線:400-618-4000

python實(shí)現(xiàn)字符串反轉(zhuǎn)的幾種方法

更新時(shí)間:2018年08月09日13時(shí)50分 來(lái)源:傳智播客 瀏覽次數(shù):

python實(shí)現(xiàn)字符串反轉(zhuǎn)的幾種方法


定義一個(gè)字符串 str = 'abcdef'
[Python] 純文本查看 復(fù)制代碼
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() 函數(shù)
my_list = list(str)
my_list.reverse()
result = ''.join(my_list)
print(result)
# 3.使用reduce() 函數(shù)
from functools import reduce
result = reduce(lambda x, y: y+x, str)
print(result)
# 4.使用遞歸函數(shù)
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)

作者:傳智播客人工智能+python培訓(xùn)學(xué)院
首發(fā):http://python.itcast.cn/
0 分享到:
和我們?cè)诰€交談!