![](/img/trans.png)
[英]Counting the pairs in a list such that their first index is less than the second but the first element is greater than the second
[英]If the first index is greater than or equal to the second the result is an empty string
在python切片中'如果第一個索引大於或等於第二個索引,則結果為空字符串'那么為什么以下操作返回字符串?
>>> msg = 'HelloWorld'
>>> msg[4:-2]
'oWor'
您提供的報價不正確或不完整:
如果使用負數,它將用作文件上的反向索引,這意味着[4:-2]
等效於[4:len(msg)-2]
即[4:8]
請注意,如果使用反向索引比第一個索引更遠,則確實會有一個空字符串。
msg[4:-8] # Equivalent to msg[4:1], by the same formula
>>> ''
python切片中的負數有效地從正數向后工作。 它們從字符串的末尾開始並向前移動。 所以您的代碼說的是給我一個字符串,該字符串從第4個索引開始,一直到最后的2個為止。
如果索引為負,則從右開始計數。 -1是最后一個字符。 要從正確的索引位置訪問字符串,我們需要使用-帶有索引號。 因此,對於-2來說,它將像帶字符直到l之前(對於給定的示例),並且其總長度必須為4。因此,它僅是應有的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.