Python 中 [::-1] 是用來做什麼的?
Python 中的分片從字串中獲取子字串。分片範圍設定為引數,即開始、停止和步長。對於分片,第一個索引是 0。
對於負索引,要以 1 為步長反向顯示第一個元素到最後一個元素,我們使用 [::-1]。[::-1] 會顛倒順序。
透過類似的方式,我們可以這樣對字串進行分片。
# slicing from index start to index stop-1 arr[start:stop] # slicing from index start to the end arr[start:] # slicing from the beginning to index stop - 1 arr[:stop] # slicing from the index start to index stop, by skipping step arr[start:stop:step] # slicing from 1st to last in steps of 1 in reverse order arr[::-1]
請記住,步長的負數表示“反向順序”。下面讓我們看一些示例 −
在 Python 中顛倒字串的順序
在 Python 中使用 [::-1] 顛倒字串的順序 −
示例
myStr = 'Hello! How are you?' print("String = ", myStr) # Slice print("Reverse order of the String = ", myStr[::-1])
輸出
String = Hello! How are you? Reverse order of the String = ?uoy era woH !olleH
顛倒 Pandas DataFrame 的行
示例
在 Python 中使用 [::-1] 顛倒資料框的行 -
import pandas as pd # Create a Dictionary dct = {'Rank':[1,2,3,4,5], 'Points':[100,87, 80,70, 50]} # Create a DataFrame from Dictionary elements using pandas.dataframe() df = pd.DataFrame(dct) print("DataFrame = \n",df) # Reverse the DataFrame using [::-1] print("\nReverse the DataFrame = \n",df[::-1])
輸出
DataFrame = Rank Points 0 1 100 1 2 87 2 3 80 3 4 70 4 5 50Reverse the DataFrame = Rank Points 4 5 50 3 4 70 2 3 80 1 2 87 0 1 100
透過分片顯示文字檔案的內容的反向順序
我們將以反向順序顯示文字檔案的內容。為此,讓我們首先建立一個文字檔案 amit.txt,內容如下 -
示例
現在讓我們以相反的順序讀取上述檔案的內容 -
# The file to be read with open("amit.txt", "r") as myfile: my_data = myfile.read() # Reversing the data by passing -1 for [start: end: step] rev_data = my_data[::-1] # Displaying the reversed data print("Reversed data = ",rev_data)
輸出
Reversed data = !tisisihT
廣告