字符串反转python_Python实现字符串反转

将字符串 s=‘helloword’ 反转输出为 ‘drowolleh’,以下通过多种方法实现

1、字符串切片法(常用)

s='helloword'r=s[::-1]print(r)#结果:drowolleh

2、使用reduce

reduce() 函数会对参数序列中元素进行累积。

函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。

from functools importreduce

s='helloword'r= reduce(lambda x,y:y+x,s) #lambda匿名函数,冒号前为参数,冒号后为表达式

print(r)#结果:drowolleh

3、使用递归函数

deffunc(s):if len(s) <1:returnsreturn func(s[1:])+s[0]

r=func(s)print(r)#结果:drowolleh

4、使用栈

deffunc(s):

l= list(s) #模拟全部入栈

result = ""

while len(l)>0:

result+= l.pop() #模拟出栈,pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

returnresult

r=func(s)print(r)#结果:drowolleh

5、for循环

deffunc(s):

result= ""max_index= len(s)-1

for index,value in enumerate(s): #enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

result += s[max_index-index]returnresult

r=func(s)print(r)#结果:drowolleh

6、使用列表的reverse方法

该方法没有返回值,但是会对列表的元素进行反向排序

s='helloword'l=list(s)

l.reverse()print("".join(l)) #把列表里的值拼接成一个字符串#print("".join(l[::-1]))

#结果:drowolleh

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值