Python中字符串反转常用的五种方法:使用字符串切片、使用递归、使用列表reverse()方法、使用栈和使用for循环。
1、使用字符串切片(最简洁)
s = "hello" reversed_s = s[::-1] print(reversed_s) >>> olleh
def reverse_it(string): if len(string)==0: return string else: return reverse_it(string[1:]) + string[0] print "added " + string[0] string1 = "the crazy programmer" string2 = reverse_it(string1) print "original = " + string1 print "reversed = " + string2
In [25]: l=['a', 'b', 'c', 'd'] ...: l.reverse() ...: print (l) ['d', 'c', 'b', 'a']
def rev_string(a_string): l = list(a_string) #模拟全部入栈 new_string = "" while len(l)>0: new_string += l.pop() #模拟出栈 return new_string
5、使用for循环
#for循环 def func(s): r = "" max_index = len(s) - 1 for index,value in enumerate(s): r += s[max_index-index] return r r = func(s)
以上就是Python中字符串反转常用的五种方法,希望能对你Python字符串的学习有所帮助~