Python [::-1]是什么意思

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的文本文件,其中包含以下内容 –

Python <code>[::-1]</code>是什么意思” title=”Python <code>[::-1]</code>是什么意思” /></p>
<h3>示例</h3>
<p>现在让我们以反向顺序读取上述文件的内容 –</p><div id=

# 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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程