高级技巧:切片,迭代,列表,生成器
切片
L = ['Hello', 'World', '!']
print("-------1.一个一个取-------")
print(L[0])
print(L[1])
print(L[2])
print("-------2.开辟一个新列表把内容存进去-------")
r = []
for i in range(3):
r.append(L[i])
print(r)
print("-------3.切片操作-------")
print("L[0:3]", L[0:3])
print("L[:3]", L[:3])
print("L[1:3]", L[1:3])
print("L[-1]", L[-1])
print("L[-2:]", L[-2:])
print("L[-2:-1]", L[-2:-1])
print("_____________切片操作详解——————————————————————")
L = list(range(1, 100))
print(L)
print(L[:10])
print(L[5:10])
print(L[-10])
print(L[-10:])
print(L[:-80])
print(L[10:-80])
print("前10个数每隔2个取一个")
print(L[::])
print(L[:10:2])
print("所有数每隔5个取一个")
print(L[::5])
print("一个例题,把字符串前后的空格删除")
def trim(s):
length = len(s) - 1
if length < 0:
return ''
last = length
while s[ length ] == ' ' :
length -= 1
last = length
if length < 0:
return ''
first = 0
while s[first] == ' ':
first += 1
last += 1
l = s[first:last]
return l
if trim('hello ') != 'hello':
print('测试失败!')
elif trim(' hello') != 'hello':
print('测试失败!')
elif trim(' hello ') != 'hello':
print('测试失败!')
elif trim(' hello world ') != 'hello worl