如何实现python字符串反转?
发布时间:2025-11-21 11:21:11

Python中常用的字符串反转五种方法:使用字符串切片,使用递归,使用列表reverse()方法使用栈和for循环。
1、使用字符串切片(最简单)
s="hello" reversed_s=s[::-1] print(reversed_s) >>>olleh2、使用递归
defreverse_it(string): iflen(string)==0: returnstring else: returnreverse_it(string[1:])+string[0] print"added"+string[0] string1="thecrazyprogrammer" string2=reverse_it(string1) print"original="+string1 print"reversed="+string23、使用列表reverse()方法
In[25]:l=['a','b','c','d'] ...:l.reverse() ...:print(l) ['d','c','b','a']4、使用栈
defrev_string(a_string): l=list(a_string)#所有的模拟都进入栈中 new_string="" whilelen(l)>0: new_string+=l.pop()#模拟堆栈 returnnew_string
5、使用for循环
#for循环 deffunc(s): r="" max_index=len(s)-1 forindex,valueinenumerate(s): r+=s[max_index-index] returnr r=func(s)
以上是Python中字符串反转的五种常用方法,希望能帮助你学习Python字符串~
