Python 切片

 1 >>> List=[1,2,3,4,5,6,7]  
 2 >>> List[:4]  #取索引为0到4的值,索引为4的值取不到
 3 [1, 2, 3, 4]
 4 >>> List[0:4]  #和上面的一样,起始不输入默认从索引0开始
 5 [1, 2, 3, 4]
 6 >>> List[-1:]  #取末尾的值
 7 [7]
 8 >>> List[-2:-1]  #取索引为-2到-1的值,索引为-1的值取不到
 9 [6]
10 >>> List[:4:2]  #取前四位的值,每隔两位输出
11 [1, 3]

定义一个利用切片来去除字符串首位空格的函数

def trim(s):
    while s[0:1]==' ':
        s=s[1:]
    while s[-1:]==' ':
        s=s[0:-1]
    return s

print(trim('strive '))
print(trim('   strive'))
越努力,越幸运
原文地址:https://www.cnblogs.com/strive99/p/10177540.html