Python实现字符串反转的6种方法
短信预约 -IT技能 免费直播动态提醒
1.使用字符串切片
>>> s = "python">>> s[::-1]'nohtyp'>>>
2.使用列表的reverse方法
>>> s = "python">>> lst = list(s)>>> lst.reverse()>>> "".join(lst)'nohtyp'>>>
手写 reverse
>>> def reverseString(s:str) -> str: lst = list(s) i, j = 0, len(s)-1 while i < j: lst[i], lst[j] = lst[j], lst[i] i , j = i + 1, j - 1 return "".join(lst) >>> s = 'python'>>> reverseString(s)'nohtyp'>>>
3.使用reduce
>>> from functools import reduce # Python3 中不可以直接调用reduce>>> s = "python">>> reduce(lambda x, y: y+x, s)'nohtyp'>>>
reduce 函数帮助:
>>> help(reduce)Help on built-in function reduce in module _functools: reduce(...) reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. >>>
4.使用递归函数
>>> def reverse(s): if s == "": return s else: return reverse(s[1:]) + s[0] >>> reverse('python')'nohtyp'>>>
python中默认的最大递归数:
>>> import sys>>> sys.getrecursionlimit()1000>>>
5.使用栈
>>> def rev(s): lst = list(s) # 转换成list ret = "" while len(lst): ret += lst.pop() # 每次弹出最后的元素 return ret#Python小白学习交流群:711312441 >>> s = 'python'>>> rev(s)'nohtyp'>>>
6.for循环
>>> def rever(s): ret = "" for i in range(len(s)-1, 0, -1): ret += s[i] return ret >>> s = "python">>> rev(s)'nohtyp'>>>
来源地址:https://blog.csdn.net/Python_222/article/details/130108777
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341