Python高階特性——切片
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('測試成功!')