如何实现python字符串反转?
695次观看1、使用字符串切片(最简洁)
s = "hello"
reversed_s = s[::-1]
print(reversed_s)
>>> olleh
2、使用递归
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
3、使用列表reverse()方法
In [25]: l=['a', 'b', 'c', 'd']
...: l.reverse()
...: print (l)
['d', 'c', 'b', 'a']
4、使用栈
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)
©本文版权归环球青藤所有,任何形式转载请联系我们。