python如何翻转字符串?
发布时间:2025-12-10 16:57:36

python中翻转字符串的方法:
1、通过字符串切片翻转
>>>s='123456' >>>print(s[::-1]) 654321
2、使用列表中的reverse()翻转字符串
>>>s='123456'
>>>ls=list(s)
>>>ls.reverse()
>>>ls
['6','5','4','3','2','1']
>>>print(''.join(ls))
6543213、使用reduce()函数实现
如果是python,请注意python版本。 2.reduce()是可以直接使用的内置函数;但是在python 3,reduce()从内置函数中删除,放入functols模块,因此需要从functols中导入。我在这里使用python 3:
>>>s='123456' >>>fromfunctoolsimportreduce >>>reduce(lambdax,y:y+x,s) '654321' >>>reduce(lambdax,y:x+y,s) '123456'
更多Python知识请关注Python自学网
下一篇 返回列表
