1.字符串切片
s = "hello" reversed_s = s[::-1] print(reversed_s) >>> olleh
2.列表的reverse方法
s = "hello" l = list(s) l.reverse() reversed_s = "".join(l) print(s) >>> olleh
3.使用reduce函数
在python2中可直接使用reduce函数,在python3中需在functools库里导入。
reduce函数语法:
reduce(function, iterable[, initializer]) function--函数,有两个参数 iterable--可迭代对象 initializer--可选,初始参数
使用方法如下:
from functools import reduce def add(x,y): return x+y res = reduce(add, [1,2,3,4,5]) print(res) >>> 15
from functools import reduce s = "hello" reversed_s = reduce(lambda x, y: y+x, s) print(reversed_s) >>>olleh
4.python3 reversed函数
reversed函数返回一个反转的迭代器
语法:
reversed(seq) seq--需要转换的序列,可以是元组,列表,字符串等。
s = "hello" l = list(reversed(s)) reversed_s = ‘‘.join(l) print(s) >>>olleh
5.使用递归函数
def func(s): if len(s) < 1: return s return func(s[1:]) +s[0] s = ‘hello‘ result = func(s) print(result) >>> olleh
6.使用栈
s = "hello" l = list(s) result = "" while(len(l)>0): result += l.pop() print(result) >>>olleh
7.for循环
s = ‘hello‘ l = list(s) for i in range(int(len(s)/2)): tmp = l[i] l[i] = l[len(s)-i-1] l[len(s)-i-1] = tmp print(‘‘.join(l)) >>>olleh
原文地址:https://www.cnblogs.com/lovewhale1997/p/11364256.html
时间: 2024-10-15 05:09:41