如何在 Python 中反轉字串
學習如何在 Python 中反轉字串。
Python 沒有內建函式來反轉字串。
最快(也許也是最簡單?)的方法是使用向後步進的切片,-1
。
示例解釋
我們有一個字串 "Hello World",想反轉它
要反轉的字串
txt = "Hello World"[::-1]
print(txt)
建立一個從字串末尾開始,向後移動的切片。
在這個具體的例子中,切片語句 [::-1]
表示從字串末尾開始,到位置 0 結束,以步長 -1
(負一)進行移動,這意味著向後移動一步。
切片字串
txt = "Hello World"[::-1]
print(txt)
現在我們有了一個字串 txt
,它反過來讀是 "Hello World"。
列印字串以演示結果
列印列表
txt = "Hello World"[::-1]
print(txt)
建立函式
如果你想建立一個函式,可以傳送字串並將其反轉,你可以建立一個函式並插入上面示例中的程式碼。
示例
def my_function(x)
return x[::-1]
mytxt = my_function("I wonder how this text looks like backwards")
print(mytxt)
自己動手試一試 »
示例解釋
建立一個以字串作為引數的函式。
建立函式
def my_function(x)
return x[::-1]
mytxt = my_function("I wonder how this text looks like backwards")
print(mytxt)
從字串末尾開始切片字串並向後移動。
切片字串
def my_function(x):
return x[::-1]
mytxt = my_function("I wonder how this text looks like backwards")
print(mytxt)
返回反轉後的字串
返回字串
def my_function(x):
return x[::-1]
mytxt = my_function("I wonder how this text looks like backwards")
print(mytxt )
呼叫函式,並將字串作為引數傳遞
呼叫函式
def my_function(x):
return x[::-1]
mytxt = my_function("I wonder how this text looks like backwards")
print(mytxt)
列印結果
列印結果
def my_function(x):
return x[::-1]
mytxt = my_function("I wonder how this text looks like backwards")
print(mytxt)