问答详情

如何实现python字符串反转?

644次观看
标签: 字符串 如何实现 python
老师回答

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)

免费直播

    精选课程
    相关推荐

    注册电脑版

    版权所有 2003-2020 广州环球青藤科技发展有限公司