Python高级特性一(切片):
有序列表元组的切片:
L=list(range(100))——生成0~100的自然数
取前十位——L[:10]
取前十位,每两位取一位——L[:10:2]
取80~90——L[80:90]或者L[-20:-10]
取所有数,每五个取一个——L[::5]
截取空格,eg:
截取空格(两种方法):
def trim(s):
if s[:1]!=' 'and s[-1:]!=' ':
return s
elif s[:1]==' ':
return trim(s[1:])
else:
return trim(s[:-1])
def trim(s):
length=len(s)
if length>0:
for i in range(length):
if s[i]!=' ':
break
j=length-1
while s[j]==' 'and j>=i:
j-=1
s=s[i:j+1]
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('测试成功!')