Python实现字符串反转

将字符串 s=‘helloword’ 反转输出为 ‘drowolleh’,以下通过多种方法实现

1、字符串切片法(常用)

s='helloword'
r=s[::-1]
print(r)

#结果:drowolleh

2、使用reduce

from functools import reduce

s='helloword'
r = reduce(lambda x,y:y+x,s)
print(r)

#结果:drowolleh

3、使用递归函数

def func(s):
    if len(s) <1:
        return s
    return func(s[1:])+s[0]
r = func(s)
print(r)

#结果:drowolleh

4、使用栈

def func(s):
    l = list(s) #模拟全部入栈
    result = ""
    while len(l)>0:
        result += l.pop() #模拟出栈
    return result
r = func(s)
print(r)

#结果:drowolleh

5、for循环

def func(s):
    result = ""
    max_index = len(s)-1
    for index,value in enumerate(s):
        result += s[max_index-index]
    return result
r = func(s)
print(r)

#结果:drowolleh

 

猜你喜欢

转载自www.cnblogs.com/jasmine0627/p/9510296.html