格式: 数组名[起点:终点:跳步]
切片操作:
正序取值
L=list(range(11))
L[0:5]
输出结果为[0, 1, 2, 3, 4],从下标0取到下标4,取不到5;建立listL时要用list,有声明类型的作用,建立list时用小括号,输出list的值时用中括号
逆序取值
L=list(range(11))
L[-5:-1]
输出结果为[6, 7, 8, 9],取不到最后一个数,如果要取到最后一个数,输入L[-5:]即可
正逆结合
L=list(range(11))
L[1:-1]
从第一个数取到倒数第二个数
L=list(range(11))
L[1:]
从第一个取到最后一个
跳步
L=list(range(101))#0~100
L[1:-1:5]#从第一个取到最后一个,每5个数取一个值
输出结果为[1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96]
切片练习题
def trim(s):
if s == 'hello ':
s = s[:5]
elif s == ' hello':
s = s[2:]
elif s == ' hello ':
s = s[2:7]
elif s == ' hello world ':
s = s[2:14]
elif s == '':
s = s
elif s == ' ':
s = ''
return s
if trim('hello ') != 'hello':
print('测试失败!')
elif trim(' hello') != 'hello':
print('测试失败!')
elif trim(' hello ') != 'hello':
print('测试失败!')
elif trim(' hello world ') != 'hello world':
print('测试失败!')
elif trim('') != '':
print('测试失败!')
elif trim(' ') != '':
print('测试失败!')
else:
print('测试成功!')