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中颠倒字符串的顺序
使用[ ::- 1]
来颠倒Python中字符串的顺序 –
示例
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的行
示例
使用[::-1]
来反转Python中的dataframe的行-
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的文本文件,其中包含以下内容 –