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 中不可以直接調(diào)用reduce
>>> s = "python"
>>> reduce(lambda x, y: y+x, s)
'nohtyp'
>>>
reduce 函數(shù)幫助:文章來源:http://www.zghlxwxcb.cn/news/detail-595297.html
>>> 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.使用遞歸函數(shù)
>>> def reverse(s):
if s == "":
return s
else:
return reverse(s[1:]) + s[0]
>>> reverse('python')
'nohtyp'
>>>
python中默認(rèn)的最大遞歸數(shù):文章來源地址http://www.zghlxwxcb.cn/news/detail-595297.html
>>> import sys
>>> sys.getrecursionlimit()
1000
>>>
5.使用棧
>>> def rev(s):
lst = list(s) # 轉(zhuǎn)換成list
ret = ""
while len(lst):
ret += lst.pop() # 每次彈出最后的元素
return ret
#Python小白學(xué)習(xí)交流群:711312441
>>> s = 'python'
>>> rev(s)
'nohtyp'
>>>
6.for循環(huán)
>>> def rever(s):
ret = ""
for i in range(len(s)-1, 0, -1):
ret += s[i]
return ret
>>> s = "python"
>>> rev(s)
'nohtyp'
>>>
到了這里,關(guān)于Python實現(xiàn)字符串反轉(zhuǎn)的6種方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!