乐鱼电竞



教育行业A股IPO第一股(股票代码 003032)

全国咨询/投诉热线:400-618-4000

python实现字符串反转的几种方法

更新时间:2018年08月09日13时50分 来源:乐鱼播客 浏览次数:

python实现字符串反转的几种方法


定义一个字符串 str = 'abcdef'
[Python] 纯文本查看 复制代码
?
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循环
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培训学院
首发:http://python.itcast.cn/
0 分享到:
和我们在线交谈!
【网站地图】【sitemap】