Python 什么是负索引
负索引用于在Python中从字符串的末尾开始切片。切片是从字符串中获取子字符串的操作。切片范围由参数设置,即起始位置、结束位置和步长。
语法
让我们来看一下语法:
#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]
如果上面的值为负数,则表示负索引,即从字符串末尾切片。
# Create a String
myStr = 'Thisisit!'
# Display the String
print("String = ", myStr)
# Slice the string
# Negative Indexing
print("String after slicing (negative indexing) = ", myStr[-4:-1])
输出
String = Thisisit!
String after slicing (negative indexing) = sit
使用负索引和步长对字符串进行切片
切片范围通过参数设置,即 开始位置、 结束位置 和 步长 。对于负索引,将 开始位置 和 结束位置 设置为负值,即从末尾开始切片 –
示例
# Create a String
myStr = 'Thisisit. We did it!'
# Display the String
print("String = ", myStr)
#Slice the string
# Negative Indexing with step
print("String after slicing (negative indexing) = ", myStr[-9:-3:2])
输出
String = Thisisit. We did it!
String after slicing (negative indexing) = edd
使用负索引对字符串进行逆序排列
为了以逆序的方式以步长为1显示第一个元素到最后一个元素,我们使用 [::-1] . [::-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