[Python commonly used small tools] Python implements string reversal

The first: use string slicing

result = s[::-1]

The second: use the reverse method of the list

l = list(s)
l.reverse()
result = "".join(l)

Of course the following works

l = list(s)
result = "".join(l[::-1])

The third type: use reduce

result = reduce(lambda x,y:y+x,s)

Fourth: use recursive functions

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

Fifth: Use the stack

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

Sixth: for loop

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

Seventh: List comprehension

s = "python"
print("".join([s[-i] for i in range(1, len(s) + 1)]))

Guess you like

Origin blog.csdn.net/weixin_51656605/article/details/112279056