python 實現字符串反轉的幾種方法


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

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM