今天就稍微的整理了一下,就發出來了,希望能幫助到大家!
字串是python中最最最常見的資料型別之一了
比如給定你 string='abcdefg'
冷的一下問你這個問題,還有可能把你問住了!
下面就是我整理的幾個方法,簡單易懂,初學者都能看懂!
第一種方法:切片實現 實用簡單 推薦使用
1 string='view codeabcdefg'2
print(string[::-1])
第二種方法 使用reduce 顯得更高大上 慢
1 reduce(lambda x,y : y+x, a_string)view code
第三種方法 使用列表 迴圈拼接 慢
1 string='view codeabcdefg
'2 lst=
3lst.extend(string)
4lst.reverse()
5 new_string = ''
6for st in
lst:
7 new_string = new_string +st
8print(new_string)
第四種,根據長度,得到最後乙個索引值,迴圈按照索引從後面取值, 不寫**演示了
還可以使用棧實現, 這些方法只有第一種的速度是最快的,而且最簡單,收藏了吧! 整理不易!
Python實現字串反轉
題目描述 現有字串strs,現要將其進行反轉。輸入 abcde 輸出 edcba 方法一 使用字串切片 coding utf 8 strs input res strs 1 print res 方法二 使用join函式進行連線 coding utf 8 strs input strs list fo...
Python實現字串反轉
將字串 s helloword 反轉輸出為 drowolleh 以下通過多種方法實現 s helloword r s 1 print r 結果 drowolleh reduce 函式會對引數序列中元素進行累積。函式將乙個資料集合 鍊錶,元組等 中的所有資料進行下列操作 用傳給 reduce 中的函式...
如何反轉字串
按單詞反轉字串是一道很常見的面試題。在python中實現起來非常簡單。def reverse string by word s lst s.split split by blank space by default return join lst 1 s power of love print re...