简体   繁体   English

切片如何与双方括号一起工作?

[英]How does slicing work with double square brackets?

I created a string variable stro .我创建了一个字符串变量stro

How will the slicing stro[7:][-6] work on stro ?如何将切片stro[7:][-6]工作stro

stro = "Python is fun"

print(stro[7:][-6])

# output: i

You are slicing, then indexing:您正在切片,然后编制索引:

stro = "Python is fun"
x = stro[7:]  # 'is fun'
y = x[-6]     # 'i'

Since strings are immutable, both x and y are new strings rather than a "view" of an object.由于字符串是不可变的,因此xy都是新字符串而不是对象的“视图”。 Thus stro[7:] returns 'is fun' and indexing the 6th last character returns 'i' .因此stro[7:]返回'is fun'并且索引第 6 个最后一个字符返回'i'

The syntax is similar to lists: see Understanding Python's slice notation .语法类似于列表:请参阅了解 Python 的切片表示法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM