Python中的负数索引是什么?


负数索引用于 Python 中从字符串末尾(即最后一个)开始切片。 在 Python 中切片 可从字符串中获取子字符串。切片范围设置为参数,即 startstopstep

语法

让我们看看语法 −

#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

用负数索引切片一个字符串并设置一个步长

切片范围设置为参数,即 startstopstep。对于负数索引,将 startstop 设置为负值,即从末尾开始切片 −

示例

# 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

更新于:2023 年 8 月 25 日

40,000+ 次浏览

开启您的 职业 生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.