简体   繁体   中英

Someone help me understand the square bracket in the following Python code?

import xlrd
book = xlrd.open_workbook("univ_list.xls")
sh = book.sheet_by_index(0)
for r in range(sh.nrows)[1:]: # line 4
    print sh.row(r)[:4] # line 5

What does [1:] mean in line 4? What does [:4] mean in line 5?

Here's an example of what you're seeing on Wikipedia: http://en.wikipedia.org/wiki/Array_slicing#1991:_Python

It's called array slicing. [1:] gets all the items except for the first, and [:4] gets the first 4 items.

[1:] means you just want to get the items from position 1 on in your list, string, etc.

[:4] means you want to get up to item 4 in your string or list.

Remember, numbering starts at 0.

so in f = 'apple', f[0]='a', f[1]='p', f[1:]='pple'

Read up on slice notation -- there's a lot more you can do with that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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