【Python】切片操作符

来源:互联网 发布:unity arpg战斗源码 编辑:程序博客网 时间:2024/05/24 06:50

python之切片操作符(Slice) 
http://blog.chinaunix.net/uid-24485075-id-3207743.html
字符串、列表、元组在python中都符合“序列”这一特征,只要符合这一特征的变量我们都可以用切片(slice)去存取它们的任意部分。我们可以把序列想像成一个队列,我可能需要前面三位、后面三位、或从第三位后的四位、或隔一个取一个等,我们用切片操作符来实现上述要求。 
切片操作符在python中的原型是 

[start:stop:step] 
即:[开始索引:结束索引:步长值] 
开始索引:同其它语言一样,从0开始。序列从左向右方向中,第一个值的索引为0,最后一个为-1 
结束索引:切片操作符将取到该索引为止,不包含该索引的值。 
步长值:默认是一个接着一个切取,如果为2,则表示进行隔一取一操作。步长值为正时表示从左向右取,如果为负,则表示从右向左取。步长值不能为0 
假设: 
li = [1,2,3,4,5,6,7] 
print li[2]                      #输出3,因为索引为2的值为3 
print li[2:4]                   #输出[3,4]。从索引2开始取,到索引为4的5为止(不含5) 
print li[-1]                     #输出7,反向取第一个 
print li[-1:-5:2]              #输出空列表[],从反向第1个向反向第5个取,但步长为2,表示正向相隔二个取值。 
print li[-1:-5:-2]            #输出[7,5] 
有时我们可以省略开始索引、结束索引,如: 
li = [1,2,3,4,5,6,7] 
print li[1:]           #输出[2,3,4,5,6,7],省略终止索引,表示取起始索引之后的所有值,等效于li[1:len(li)] 
print li[:3]           #输出[1,2,3],省略起始索引,表示从0开始取,等效于li[0:3] 
print li[:]            #输出[1,2,3,4,5,6,7],省略起始索引、终止索引、步长值表示取全部,等效于li[0:len(li):1] 
print li[::]           #输出[1,2,3,4,5,6,7],省略起始索引、终止索引、步长值表示取全部,等效于li[0:len(li):1] 
print li[::-1]        #输出[7,6,5,4,3,2,1],省略起始索引、终止索引,步长值为-1,表示反向获取 
所以,不要为str类没有substring方法而感到困惑,用切片操作符吧。 

def reverse(text):    ''' '''    return text[::-1]def is_palindrome(text):    text = text.lower()    text = text.replace(' ','')#remove blank space    for char in text.punctuation:        text = text.replace(char,'')    return text == reverse(text)def main():    string = input("Please input a string: ")    if is_palindrome(string):        print("Yes, '{0}' is palindrome!".format(string))    else:        print("No, '{0}' isn't palindrome!".format(string))        if __name__ == '__main__':    main()else:    pring("user_input.py was imported.")>>> array = [1, 2, 5, 3, 6, 8, 4] index为:     0, 1, 2, 3, 4, 5, 6array[start : stop : step]>>> array[:2][1, 2] #输出[array[0],array[2])的元素, 不包括array[2]>>> array[2:][5, 3, 6, 8, 4] # 输出从array[2]开始的所有元素>>> array[::2][1, 5, 6, 4] # 从array起始到结束, 以2为步长输出元素>>> help(str.replace)Help on method_descriptor:replace(...)    S.replace(old, new[, count]) -> str        Return a copy of S with all occurrences of substring    old replaced by new.  If the optional argument count is    given, only the first count occurrences are replaced.>>> word = "this is a test">>> word.replace("is", "eez")'theez eez a test'>>> word'this is a test'


0 0
原创粉丝点击