首页 > 编程语言 > 详细

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

时间:2019-10-22 09:31:30      阅读:85      评论:0      收藏:0      [点我收藏+]

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):

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

原文:https://www.cnblogs.com/heimaguangzhou/p/11717727.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!