本文摘自php中文网,作者silencement,侵删。
反转方法:1、使用切片法来反转,语法“字符串[::-1]”。2、首先将字符串转换成列表;然后使用reverse()反转列表元素;最后将反转的列表转换会字符串即可。3、使用reduce()函数,语法“reduce(lambda x,y:y+x,字符串)”。

面试遇到的一个特无聊的问题~~~
要求:在Python环境下用尽可能多的方法反转字符串,例如将s = "abcdef"反转成 "fedcba"
第一种:使用字符串切片
1 2 3 | >>> s= "abcdef"
>>> result = s[::-1]
>>> print (result)
|
输出:
第二种:使用列表的reverse方法
1 2 3 | l = list(s)
l.reverse()
result = "" .join(l)
|
当然下面也行
1 2 | l = list(s)
result = "" .join(l[::-1])
|
第三种:使用reduce
1 | result = reduce(lambda x,y:y+x,s)
|
第四种:使用递归函数
1 2 3 4 5 | def func(s):
if len(s) <1:
return s
return func(s[1:])+s[0]
result = func(s)
|
第五种:使用栈
1 2 3 4 5 6 7 | def func(s):
l = list(s) #模拟全部入栈
result = ""
while len(l)>0:
result += l.pop() #模拟出栈
return result
result = func(s)
|
第六种:for循环
1 2 3 4 5 6 7 | def func(s):
result = ""
max_index = len(s)-1
for index,value in enumerate(s):
result += s[max_index-index]
return result
result = func(s)
|
以上就是Python如何反转字符串的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
学Python必须装虚拟机吗
Python axis是什么意思
Python中index是什么
java与Python中单例模式的区别
Python爬虫一般都爬什么信息
大学有Python课吗
配置opencv3+Python3的方法
Python 异常处理机制详解
Python基于百度ai的文字识别的示例
Python列表list
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python如何反转字符串