Python实现字符串反转的几种方法
这是一道面试题,要求在Python环境下用尽可能多的方法反转字符串,例如将s = “abcdef”反转成 “fedcba” 。
方法1:字符串切片
1result = s[::-1]
方法2:使用列表的reverse方法
1l = list(s)
2l.reverse()
3result = "".join(l)
4或者
5l = list(s)
6result = "".join(l[::-1])
方法3:使用reduce
1result = reduce(lambda x,y:y+x,s)
方法4:使用递归函数
1def func(s):
2 if len(s) <1:
3 return s
4 return func(s[1:])+s[0]
5result = func(s)
方法5:使用栈
1def func(s):
2 l = list(s) #模拟全部入栈
3 result = ""
4 while len(l)>0:
5 result += l.pop() #模拟出栈
6 return result
7result = func(s)
方法6:for循环
1def func(s):
2 result = ""
3 max_index = len(s)-1
4 for index,value in enumerate(s):
5 result += s[max_index-index]
6 return result
7result = func(s)
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/python-string-reverse/6007.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.