本文摘自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怎么读文件
geany中怎么配置Python?
Python怎么限制浮点型到小数点后两位
Pythonde 朴素贝叶斯算法
Python中关于string相关操作的实例分析
Python如何计算列表中元素出现的个数
Python对文件操作流程介绍
Python里floor怎么用
Python中flask应用(表单处理)
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python如何反转字符串