如何反轉python中的字串

2022-08-09 05:54:08 字數 413 閱讀 2157

在 python 中沒有內建函式來反轉字串。

最快(也是最簡單?)的方法是使用向後退步的切片,-1。

反轉字串 "hello world":

txt = "hello world"[::-1]

print(txt)

我們有個字串,"hello world",我們要反轉它:

txt = "hello world" [::-1]

print(txt)

建立乙個從字串末尾開始的切片,然後向後移動。

在這個特定的例子中,slice 語句 [::-1] 等同於 [11:0:-1],這意味著從位置 11 開始(因為 "hello "world" 有 11 個字元),結束於位置 0,移動步長 -1,負一意味著向後退一步。

如何反轉字串

按單詞反轉字串是一道很常見的面試題。在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...

python 字串反轉

usr bin env python3 coding utf 8 filename reverse string.py author zoujiameng aliyun.com.cn 題目描述 給定乙個句子 只包含字母和空格 將句子中的單詞位置反轉,單詞用空格分割,單詞之間只有乙個空格,前後沒有空格...

Python 字串反轉

一 字串切片 簡潔 res s 1 二 借助listt的reverse 2.使用list的reverse函式 3.使用join函式將列表中元素組合成乙個字串 l list s res join l.reverse 三 使用reduce函式 result reduce lambda x,y y x,s...